Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 | 124x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 14x 33x 18x 13x 5x 1x 4x 3x 1x 18x 18x 10x 18x 18x 9x 9x 9x 10x 9x 10x 18x 21x 21x 21x 21x 1x 21x 4x 2x 4x 17x 13x 4x 1x 1x 3x 3x 3x 3x 1x 3x 1x 3x 1x 3x 1x 3x 3x 3x 1x 3x 3x 3x 3x 21x 1x 20x 21x 21x 21x 21x 3x 18x 5x 5x 21x 21x 21x 21x 1x 2x 2x 2x 2x 1x 1x 2x 21x 2x 1x 21x 21x 1x 21x 3x 3x 3x 3x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 8x 8x 11x 11x 11x 2x 11x 33x 33x 33x 33x 33x 33x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 14x 14x 12x 12x 17x 17x 17x 17x 17x 17x 18x 17x 15x 2x 6x 6x 5x 5x 6x 6x 5x 5x 5x 5x 5x 5x 1x 16x 16x 6x 10x 10x 10x 16x 16x 16x 16x 16x 14x 14x 248x 34x 8x 26x 7x 19x 214x 19x 195x 86x 193x 86x 109x 14x 14x 14x 14x 8x 14x 8x 14x 14x 16x 14x 14x 8x 8x 8x 8x 8x 6x 3x 14x 14x 14x 9x 9x 9x 4x 5x 9x 9x 9x 9x 9x 9x 2x 2x 2x 4x 7x 9x 9x 3x 3x 3x 6x 13x 38x 38x 25x 13x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 7x 16x 16x 2x 14x 26x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 13x 10x 10x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 2x 3x 3x 3x 3x 3x 3x 3x 1x 3x 5x 3x 1x 1x 1x 18x 8x 10x 10x 10x 10x 10x 1x 31x 31x 31x 1x 8x 2x 8x 8x 8x | /**
* EOSIO Signing Request (ESR).
*/
import {
ABI,
ABIDecoder,
ABIDef,
ABIEncoder,
ABISerializable,
ABISerializableConstructor,
ABISerializableType,
Action,
AnyAction,
AnyTransaction,
Bytes,
BytesType,
Checksum256,
Name,
NameType,
PermissionLevel,
PermissionLevelType,
Serializer,
Signature,
SignatureType,
TimePointSec,
TimePointType,
Transaction,
TransactionExtension,
UInt16,
UInt16Type,
UInt32,
UInt32Type,
UInt8,
VarUInt,
} from '@wharfkit/antelope'
import * as base64u from './base64u'
import {ChainAlias, ChainId, ChainIdType, ChainIdVariant, ChainName} from './chain-id'
import {
IdentityV2,
IdentityV3,
InfoPair,
RequestDataV2,
RequestDataV3,
RequestFlags,
RequestSignature,
} from './abi'
import {IdentityProof} from './identity-proof'
/** Current supported protocol version, backwards compatible with version 2. */
export const ProtocolVersion = 3
/** Interface that should be implemented by abi providers. */
export interface AbiProvider {
/**
* Return a promise that resolves to an abi object for the given account name,
* e.g. the result of a rpc call to chain/get_abi.
*/
getAbi: (account: Name) => Promise<ABIDef>
}
/** Interface that should be implemented by zlib implementations. */
export interface ZlibProvider {
/** Deflate data w/o adding zlib header. */
deflateRaw: (data: Uint8Array) => Uint8Array
/** Inflate data w/o requiring zlib header. */
inflateRaw: (data: Uint8Array) => Uint8Array
}
/** Interface that should be implemented by signature providers. */
export interface SignatureProvider {
/** Sign 32-byte message and return signer name and signature string. */
sign: (message: Checksum256) => {signer: NameType; signature: SignatureType}
}
/**
* The callback payload sent to background callbacks.
*/
export interface CallbackPayload {
/** The first signature. */
sig: string
/** Transaction ID as HEX-encoded string. */
tx: string
/** Block number hint (only present if transaction was broadcast). */
bn?: string
/** Signer authority, aka account name. */
sa: string
/** Signer permission, e.g. "active". */
sp: string
/** Reference block num used when resolving request. */
rbn: string
/** Reference block id used when resolving request. */
rid: string
/** The originating signing request packed as a uri string. */
req: string
/** Expiration time used when resolving request. */
ex: string
/** The resolved chain id. */
cid?: string
/** All signatures 0-indexed as `sig0`, `sig1`, etc. */
[sig0: string]: string | undefined
}
/**
* Context used to resolve a callback.
* Compatible with the JSON response from a `push_transaction` call.
*/
export interface ResolvedCallback {
/** The URL to hit. */
url: string
/**
* Whether to run the request in the background. For a https url this
* means POST in the background instead of a GET redirect.
*/
background: boolean
/**
* The callback payload as a object that should be encoded to JSON
* and POSTed to background callbacks.
*/
payload: CallbackPayload
}
/**
* Context used to resolve a transaction.
* Compatible with the JSON response from a `get_block` call.
*/
export interface TransactionContext {
/** Timestamp expiration will be derived from. */
timestamp?: TimePointType
/**
* How many seconds in the future to set expiration when deriving from timestamp.
* Defaults to 60 seconds if unset.
*/
expire_seconds?: UInt32Type
/** Block number ref_block_num will be derived from. */
block_num?: UInt32Type
/** Reference block number, takes precedence over block_num if both is set. */
ref_block_num?: UInt16Type
/** Reference block prefix. */
ref_block_prefix?: UInt32Type
/** Expiration timestamp, takes precedence over timestamp and expire_seconds if set. */
expiration?: TimePointType
/** Chain ID to resolve for, required for multi-chain requests. */
chainId?: ChainIdType
}
/**
* The placeholder name: `............1` aka `uint64(1)`.
* If used in action data will be resolved to current signer.
* If used in as an authorization permission will be resolved to
* the signers permission level.
*
* Example action:
* ```
* { account: "eosio.token",
* name: "transfer",
* authorization: [{actor: "............1", permission: "............1"}],
* data: {
* from: "............1",
* to: "bar",
* quantity: "42.0000 EOS",
* memo: "Don't panic" }}
* ```
* When signed by `foo@active` would resolve to:
* ```
* { account: "eosio.token",
* name: "transfer",
* authorization: [{actor: "foo", permission: "active"}],
* data: {
* from: "foo",
* to: "bar",
* quantity: "42.0000 EOS",
* memo: "Don't panic" }}
* ```
*/
export const PlaceholderName = Name.from('............1') // aka uint64(1)
/** Placeholder that will resolve to signer permission name. */
export const PlaceholderPermission = Name.from('............2') // aka uint64(2)
export const PlaceholderAuth = PermissionLevel.from({
actor: PlaceholderName,
permission: PlaceholderPermission,
})
export interface ResolvedAction {
/** The account (a.k.a. contract) to run action on. */
account: Name
/** The name of the action. */
name: Name
/** The permissions authorizing the action. */
authorization: PermissionLevel[]
/** The decoded action data. */
data: Record<string, ABISerializable>
}
export interface ResolvedTransaction {
/** The time at which a transaction expires. */
expiration: TimePointSec
/** *Specifies a block num in the last 2^16 blocks. */
ref_block_num: UInt16
/** Specifies the lower 32 bits of the block id. */
ref_block_prefix: UInt32
/** Upper limit on total network bandwidth (in 8 byte words) billed for this transaction. */
max_net_usage_words: VarUInt
/** Upper limit on the total CPU time billed for this transaction. */
max_cpu_usage_ms: UInt8
/** Number of seconds to delay this transaction for during which it may be canceled. */
delay_sec: VarUInt
/** The context free actions in the transaction. */
context_free_actions: ResolvedAction[]
/** The actions in the transaction. */
actions: ResolvedAction[]
/** Transaction extensions. */
transaction_extensions: TransactionExtension[]
}
export type CallbackType = string | {url: string; background: boolean}
interface SigningRequestCommonArguments {
/**
* Chain ID to use, can be set to `null` for a multi-chain request.
* Defaults to EOS if omitted.
*/
chainId?: ChainIdType | null
/**
* Chain IDs to constrain a multi-chain request to.
* Only considered if `chainId` is explicitly set to `null.
*/
chainIds?: ChainIdType[]
/** Optional metadata to pass along with the request. */
info?: {[key: string]: Bytes | ABISerializable}
}
export interface SigningRequestCreateArguments extends SigningRequestCommonArguments {
/** Single action to create request with. */
action?: AnyAction
/** Multiple actions to create request with. */
actions?: AnyAction[]
/**
* Full or partial transaction to create request with.
* If TAPoS info is omitted it will be filled in when resolving the request.
*/
transaction?: Partial<AnyTransaction>
/** Create an identity request. */
identity?: {
scope?: NameType
permission?: PermissionLevelType
}
/** Whether wallet should broadcast tx, defaults to true. */
broadcast?: boolean
/**
* Optional callback URL the signer should hit after
* broadcasting or signing. Passing a string means background = false.
*/
callback?: CallbackType
}
export interface SigningRequestCreateIdentityArguments extends SigningRequestCommonArguments {
/**
* Callback where the identity should be delivered.
*/
callback: CallbackType
/**
* Requested account name of identity.
* Defaults to placeholder (any identity) if omitted.
*/
account?: NameType
/**
* Requested account permission.
* Defaults to placeholder (any permission) if omitted.
*/
permission?: NameType
/**
* Scope for the request.
*/
scope?: NameType
}
export interface SigningRequestEncodingOptions {
/** Optional zlib, if provided the request will be compressed when encoding. */
zlib?: ZlibProvider
/** Abi provider, required if the arguments contain un-encoded actions. */
abiProvider?: AbiProvider
/** Optional signature provider, will be used to create a request signature if provided. */
signatureProvider?: SignatureProvider
}
export type AbiMap = Map<string, ABI>
export class SigningRequest {
/** Return the identity ABI for given version. */
private static identityAbi(version: number) {
const abi = Serializer.synthesize(this.identityType(version))
abi.actions = [{name: 'identity', type: 'identity', ricardian_contract: ''}]
return abi
}
/** Return the ABISerializableType identity type for given version. */
private static identityType(version: number): typeof IdentityV2 | typeof IdentityV3 {
return version === 2 ? IdentityV2 : IdentityV3
}
/** Return the ABISerializableType storage type for given version. */
private static storageType(version: number): typeof RequestDataV3 | typeof RequestDataV2 {
return version === 2 ? RequestDataV2 : RequestDataV3
}
/** Create a new signing request. */
public static async create(
args: SigningRequestCreateArguments,
options: SigningRequestEncodingOptions = {}
) {
let actions: AnyAction[]
if (args.action) {
actions = [args.action]
} else if (args.actions) {
actions = args.actions
} else if (args.transaction) {
actions = args.transaction.actions || []
} else {
actions = []
}
const requiredAbis = actions
.filter(
(action) =>
!Bytes.isBytes(action.data) &&
(action.data.constructor as any).abiName === undefined
)
.map((action) => Name.from(action.account))
const abis: Record<string, ABIDef> = {}
if (requiredAbis.length > 0) {
const provider = options.abiProvider
Iif (!provider) {
throw new Error('Missing abi provider')
}
const accountAbis = await Promise.all(
requiredAbis.map((account) => provider.getAbi(account))
)
for (const [idx, abi] of accountAbis.entries()) {
abis[requiredAbis[idx].toString()] = abi
}
}
return this.createSync(args, options, abis)
}
/**
* Synchronously create a new signing request.
* @throws If an un-encoded action with no abi def is encountered.
*/
public static createSync(
args: SigningRequestCreateArguments,
options: SigningRequestEncodingOptions = {},
abis: Record<string, ABIDef> = {}
) {
let version = 2
const data: any = {}
const encode = (action: AnyAction) => encodeAction(action, abis)
// multi-chain requests requires version 3
if (args.chainId === null) {
version = 3
}
// set the request data
if (args.identity !== undefined) {
if (args.identity.scope) {
version = 3
}
data.req = ['identity', this.identityType(version).from(args.identity)]
} else if (args.action && !args.actions && !args.transaction) {
data.req = ['action', encode(args.action)]
} else if (args.actions && !args.action && !args.transaction) {
Iif (args.actions.length === 1) {
data.req = ['action', encode(args.actions[0])]
} else {
data.req = ['action[]', args.actions.map(encode)]
}
} else if (args.transaction && !args.action && !args.actions) {
const tx = args.transaction
// set default values if missing
Iif (tx.expiration === undefined) {
tx.expiration = '1970-01-01T00:00:00.000'
}
if (tx.ref_block_num === undefined) {
tx.ref_block_num = 0
}
if (tx.ref_block_prefix === undefined) {
tx.ref_block_prefix = 0
}
if (tx.context_free_actions === undefined) {
tx.context_free_actions = []
}
if (tx.transaction_extensions === undefined) {
tx.transaction_extensions = []
}
Iif (tx.delay_sec === undefined) {
tx.delay_sec = 0
}
Iif (tx.max_cpu_usage_ms === undefined) {
tx.max_cpu_usage_ms = 0
}
if (tx.max_net_usage_words === undefined) {
tx.max_net_usage_words = 0
}
Iif (tx.actions === undefined) {
tx.actions = []
}
Iif (tx.context_free_actions === undefined) {
tx.context_free_actions = []
}
// encode actions if needed
tx.actions = tx.actions.map(encode)
data.req = ['transaction', tx]
} else E{
throw new TypeError(
'Invalid arguments: Must have exactly one of action, actions or transaction'
)
}
// set the chain id
if (args.chainId === null) {
data.chain_id = ChainIdVariant.from(['chain_alias', 0])
} else {
data.chain_id = ChainId.from(args.chainId || ChainName.EOS).chainVariant
}
// request flags and callback
const flags = RequestFlags.from(0)
let callback = ''
flags.broadcast = args.broadcast !== undefined ? args.broadcast : data.req[0] !== 'identity'
if (typeof args.callback === 'string') {
callback = args.callback
} else if (typeof args.callback === 'object') {
callback = args.callback.url
flags.background = args.callback.background || false
}
data.flags = flags
data.callback = callback
// info pairs
data.info = []
if (typeof args.info === 'object') {
for (const key in args.info) {
const isOwn = Object.prototype.hasOwnProperty.call(args.info, key)
if (isOwn) {
let value = args.info[key]
if (typeof value === 'string') {
value = Bytes.from(value, 'utf8')
I} else if (!(value instanceof Bytes)) {
value = Serializer.encode({object: value})
}
data.info.push({key, value})
}
}
}
if (args.chainIds && args.chainId === null) {
const ids = args.chainIds.map((id) => ChainId.from(id).chainVariant)
data.info.push({
key: 'chain_ids',
value: Serializer.encode({object: ids, type: {type: ChainIdVariant, array: true}}),
})
}
const req = new SigningRequest(
version,
this.storageType(version).from(data),
options.zlib,
options.abiProvider
)
// sign the request if given a signature provider
if (options.signatureProvider) {
req.sign(options.signatureProvider)
}
return req
}
/** Creates an identity request. */
public static identity(
args: SigningRequestCreateIdentityArguments,
options: SigningRequestEncodingOptions = {}
) {
let permission: PermissionLevelType | undefined = {
actor: args.account || PlaceholderName,
permission: args.permission || PlaceholderPermission,
}
if (
permission.actor === PlaceholderName &&
permission.permission === PlaceholderPermission
) {
permission = undefined
}
return this.createSync(
{
...args,
identity: {
permission,
scope: args.scope,
},
broadcast: false,
},
options
)
}
/**
* Create a request from a chain id and serialized transaction.
* @param chainId The chain id where the transaction is valid.
* @param serializedTransaction The serialized transaction.
* @param options Creation options.
*/
public static fromTransaction(
chainId: ChainIdType,
serializedTransaction: BytesType,
options: SigningRequestEncodingOptions = {}
) {
const id = ChainId.from(chainId)
serializedTransaction = Bytes.from(serializedTransaction)
const encoder = new ABIEncoder()
encoder.writeByte(2) // header
encoder.writeArray(Serializer.encode({object: id.chainVariant}).array)
encoder.writeByte(2) // transaction variant
encoder.writeArray(Bytes.from(serializedTransaction).array)
encoder.writeByte(RequestFlags.broadcast)
encoder.writeByte(0) // callback
encoder.writeByte(0) // info
return SigningRequest.fromData(encoder.getData(), options)
}
/** Creates a signing request from encoded `esr:` uri string. */
public static from(uri: string, options: SigningRequestEncodingOptions = {}) {
Iif (typeof uri !== 'string') {
throw new Error('Invalid request uri')
}
const [, path] = uri.split(':')
const data = base64u.decode(path.startsWith('//') ? path.slice(2) : path)
return SigningRequest.fromData(data, options)
}
public static fromData(data: BytesType, options: SigningRequestEncodingOptions = {}) {
data = Bytes.from(data)
const header = data.array[0]
const version = header & ~(1 << 7)
Iif (version !== 2 && version !== 3) {
throw new Error('Unsupported protocol version')
}
let payload = data.droppingFirst(1)
if ((header & (1 << 7)) !== 0) {
Iif (!options.zlib) {
throw new Error('Compressed URI needs zlib')
}
payload = Bytes.from(options.zlib.inflateRaw(payload.array))
}
const decoder = new ABIDecoder(payload.array)
const req = Serializer.decode({data: decoder, type: this.storageType(version)})
let sig: RequestSignature | undefined
if (decoder.canRead()) {
sig = Serializer.decode({data: decoder, type: RequestSignature}) as RequestSignature
}
return new SigningRequest(version, req, options.zlib, options.abiProvider, sig)
}
/** The signing request version. */
public version: number
/** The raw signing request data. */
public data: RequestDataV2 | RequestDataV3
/** The request signature. */
public signature?: RequestSignature
private zlib?: ZlibProvider
private abiProvider?: AbiProvider
/**
* Create a new signing request.
* Normally not used directly, see the `create` and `from` class methods.
*/
constructor(
version: number,
data: RequestDataV2 | RequestDataV3,
zlib?: ZlibProvider,
abiProvider?: AbiProvider,
signature?: RequestSignature
) {
Iif (data.flags.broadcast && data.req.variantName === 'identity') {
throw new Error('Invalid request (identity request cannot be broadcast)')
}
this.version = version
this.data = data
this.zlib = zlib
this.abiProvider = abiProvider
this.signature = signature
}
/**
* Sign the request, mutating.
* @param signatureProvider The signature provider that provides a signature for the signer.
*/
public sign(signatureProvider: SignatureProvider) {
const message = this.getSignatureDigest()
this.signature = RequestSignature.from(signatureProvider.sign(message))
}
/**
* Get the signature digest for this request.
*/
public getSignatureDigest() {
// protocol version + utf8 "request"
const prefix = [this.version, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74]
return Checksum256.hash(Bytes.from(prefix).appending(this.getData()))
}
/**
* Set the signature data for this request, mutating.
* @param signer Account name of signer.
* @param signature The signature string.
*/
public setSignature(signer: string, signature: string) {
this.signature = RequestSignature.from({signer, signature})
}
/**
* Set the request callback, mutating.
* @param url Where the callback should be sent.
* @param background Whether the callback should be sent in the background.
*/
public setCallback(url: string, background: boolean) {
this.data.callback = url
this.data.flags.background = background
}
/**
* Set broadcast flag.
* @param broadcast Whether the transaction should be broadcast by receiver.
*/
public setBroadcast(broadcast: boolean) {
this.data.flags.broadcast = broadcast
}
/**
* Encode this request into an `esr:` uri.
* @argument compress Whether to compress the request data using zlib,
* defaults to true if omitted and zlib is present;
* otherwise false.
* @argument slashes Whether add slashes after the protocol scheme, i.e. `esr://`.
* Defaults to true.
* @returns An esr uri string.
*/
public encode(compress?: boolean, slashes?: boolean, scheme: string = 'esr:'): string {
const shouldCompress = compress !== undefined ? compress : this.zlib !== undefined
Iif (shouldCompress && this.zlib === undefined) {
throw new Error('Need zlib to compress')
}
let header = this.version
const data = this.getData()
const sigData = this.getSignatureData()
let array: Uint8Array = new Uint8Array(data.byteLength + sigData.byteLength)
array.set(data, 0)
array.set(sigData, data.byteLength)
if (shouldCompress) {
const deflated = this.zlib!.deflateRaw(array)
if (array.byteLength > deflated.byteLength) {
header |= 1 << 7
array = deflated
}
}
const out = new Uint8Array(1 + array.byteLength)
out[0] = header
out.set(array, 1)
if (slashes !== false) {
scheme += '//'
}
return scheme + base64u.encode(out)
}
/** Get the request data without header or signature. */
public getData(): Uint8Array {
return Serializer.encode({object: this.data}).array
}
/** Get signature data, returns an empty array if request is not signed. */
public getSignatureData(): Uint8Array {
if (!this.signature) {
return new Uint8Array(0)
}
return Serializer.encode({object: this.signature}).array
}
/** ABI definitions required to resolve request. */
public getRequiredAbis() {
return this.getRawActions()
.filter((action) => !isIdentity(action))
.map((action) => action.account)
.filter((value, index, self) => self.indexOf(value) === index)
}
/** Whether TaPoS values are required to resolve request. */
public requiresTapos() {
const tx = this.getRawTransaction()
return !this.isIdentity() && !hasTapos(tx)
}
/** Resolve required ABI definitions. */
public async fetchAbis(abiProvider?: AbiProvider): Promise<AbiMap> {
const required = this.getRequiredAbis()
if (required.length > 0) {
const provider = abiProvider || this.abiProvider
Iif (!provider) {
throw new Error('Missing ABI provider')
}
const abis = new Map<string, any>()
await Promise.all(
required.map(async (account) => {
abis.set(account.toString(), ABI.from(await provider.getAbi(account)))
})
)
return abis
} else {
return new Map()
}
}
/**
* Decode raw actions actions to object representations.
* @param abis ABI defenitions required to decode all actions.
* @param signer Placeholders in actions will be resolved to signer if set.
*/
public resolveActions(abis: AbiMap, signer?: PermissionLevelType): ResolvedAction[] {
return this.getRawActions().map((rawAction) => {
let abi: ABI
if (isIdentity(rawAction)) {
abi = (this.constructor as typeof SigningRequest).identityAbi(this.version)
} else {
const rawAbi = abis.get(rawAction.account.toString())
Iif (!rawAbi) {
throw new Error(`Missing ABI definition for ${rawAction.account}`)
}
abi = ABI.from(rawAbi)
}
const type = abi.getActionType(rawAction.name)
Iif (!type) {
throw new Error(
`Missing type for action ${rawAction.account}:${rawAction.name} in ABI`
)
}
let data = rawAction.decodeData(abi) as Record<string, ABISerializable>
let authorization = rawAction.authorization
if (signer) {
const signerPerm = PermissionLevel.from(signer)
const resolve = (value: any): any => {
if (value instanceof Name) {
if (value.equals(PlaceholderName)) {
return signerPerm.actor
} else if (value.equals(PlaceholderPermission)) {
return signerPerm.permission
} else {
return value
}
} else if (Array.isArray(value)) {
return value.map(resolve)
} else if (typeof value === 'object' && value !== null) {
for (const key of Object.keys(value)) {
value[key] = resolve(value[key])
}
return value
} else {
return value
}
}
data = resolve(data)
authorization = authorization.map((auth) => {
let {actor, permission} = auth
if (actor.equals(PlaceholderName)) {
actor = signerPerm.actor
}
if (permission.equals(PlaceholderPermission)) {
permission = signerPerm.permission
}
// backwards compatibility, actor placeholder will also resolve to permission when used in auth
Iif (permission.equals(PlaceholderName)) {
permission = signerPerm.permission
}
return PermissionLevel.from({actor, permission})
})
}
return {
...rawAction,
authorization,
data,
}
})
}
public resolveTransaction(
abis: AbiMap,
signer: PermissionLevelType,
ctx: TransactionContext = {}
) {
const tx = this.getRawTransaction()
if (!this.isIdentity() && !hasTapos(tx)) {
Iif (
ctx.expiration !== undefined &&
ctx.ref_block_num !== undefined &&
ctx.ref_block_prefix !== undefined
) {
tx.expiration = TimePointSec.from(ctx.expiration)
tx.ref_block_num = UInt16.from(ctx.ref_block_num, 'truncate')
tx.ref_block_prefix = UInt32.from(ctx.ref_block_prefix)
} else if (
ctx.block_num !== undefined &&
ctx.ref_block_prefix !== undefined &&
ctx.timestamp !== undefined
) {
tx.expiration = expirationTime(ctx.timestamp, ctx.expire_seconds)
tx.ref_block_num = UInt16.from(ctx.block_num, 'truncate')
tx.ref_block_prefix = UInt32.from(ctx.ref_block_prefix)
} else E{
throw new Error(
'Invalid transaction context, need either a reference block or explicit TaPoS values'
)
}
} else if (this.isIdentity() && this.version > 2) {
// From ESR version 3 all identity requests have expiration
tx.expiration = ctx.expiration
? TimePointSec.from(ctx.expiration)
: expirationTime(ctx.timestamp, ctx.expire_seconds)
}
const actions = this.resolveActions(abis, signer)
// TODO: resolve context free actions
const context_free_actions = tx.context_free_actions as unknown as ResolvedAction[]
return {...tx, context_free_actions, actions} as ResolvedTransaction
}
public resolve(abis: AbiMap, signer: PermissionLevelType, ctx: TransactionContext = {}) {
const tx = this.resolveTransaction(abis, signer, ctx)
const actions = tx.actions.map((action) => {
let abi: ABI | undefined
if (isIdentity(action)) {
abi = (this.constructor as typeof SigningRequest).identityAbi(this.version)
} else {
abi = abis.get(action.account.toString())
}
Iif (!abi) {
throw new Error(`Missing ABI definition for ${action.account}`)
}
const type = abi.getActionType(action.name)!
const data = Serializer.encode({object: action.data, type, abi})
return Action.from({...action, data})
})
const transaction = Transaction.from({...tx, actions})
let chainId: ChainId
if (this.isMultiChain()) {
Iif (!ctx.chainId) {
throw new Error('Missing chosen chain ID for multi-chain request')
}
chainId = ChainId.from(ctx.chainId)
const ids = this.getChainIds()
Iif (ids && !ids.some((id) => chainId.equals(id))) {
throw new Error('Trying to resolve for chain ID not defined in request')
}
} else {
chainId = this.getChainId()
}
return new ResolvedSigningRequest(
this,
PermissionLevel.from(signer),
transaction,
tx,
chainId
)
}
/**
* Get the id of the chain where this request is valid.
* @returns The 32-byte chain id as hex encoded string.
*/
public getChainId(): ChainId {
return this.data.chain_id.chainId
}
/**
* Chain IDs this request is valid for, only valid for multi chain requests. Value of `null` when `isMultiChain` is true denotes any chain.
*/
public getChainIds(): ChainId[] | null {
Iif (!this.isMultiChain()) {
return null
}
const ids = this.getInfoKey('chain_ids', {type: ChainIdVariant, array: true}) as
| ChainIdVariant[]
| undefined
if (ids) {
return ids.map((id) => id.chainId)
}
return null
}
/**
* Set chain IDs this request is valid for, only considered for multi chain requests.
*/
public setChainIds(ids: ChainIdType[]) {
const value = ids.map((id) => ChainId.from(id).chainVariant)
this.setInfoKey('chain_ids', value, {type: ChainIdVariant, array: true})
}
/**
* True if chainId is set to chain alias `0` which indicates that the request is valid for any chain.
*/
public isMultiChain(): boolean {
return (
this.data.chain_id.variantIdx === 0 &&
(this.data.chain_id.value as ChainAlias).equals(ChainName.UNKNOWN)
)
}
/** Return the actions in this request with action data encoded. */
public getRawActions(): Action[] {
const req = this.data.req
switch (req.variantName) {
case 'action':
return [req.value as Action]
case 'action[]':
return req.value as Action[]
case 'identity': {
if (this.version === 2) {
const id = req.value as IdentityV2
let data: BytesType = '0101000000000000000200000000000000' // placeholder permission
let authorization: PermissionLevelType[] = [PlaceholderAuth]
Iif (id.permission) {
data = Serializer.encode({object: id})
authorization = [id.permission]
}
const action = Action.from({
account: '',
name: 'identity',
authorization,
data,
})
// TODO: The way payloads are encoded is including the ABI, which isn't what we want
// This needs to be resolved in wharfkit/antelope, and then the delete call here should be removed
delete action.abi
return [action]
} else {
// eslint-disable-next-line prefer-const
let {scope, permission} = req.value as IdentityV3
if (!permission) {
permission = PlaceholderAuth
}
const data = Serializer.encode({object: {scope, permission}, type: IdentityV3})
const action = Action.from({
account: '',
name: 'identity',
authorization: [permission],
data,
})
// TODO: The way payloads are encoded is including the ABI, which isn't what we want
// This needs to be resolved in wharfkit/antelope, and then the delete call here should be removed
delete action.abi
return [action]
}
}
case 'transaction':
return (req.value as Transaction).actions
default:
throw new Error('Invalid signing request data')
}
}
/** Unresolved transaction. */
public getRawTransaction(): Transaction {
const req = this.data.req
switch (req.variantName) {
case 'transaction':
return Transaction.from({...(req.value as Transaction)})
case 'action':
case 'action[]':
case 'identity':
return Transaction.from({
actions: this.getRawActions(),
context_free_actions: [],
transaction_extensions: [],
expiration: '1970-01-01T00:00:00.000',
ref_block_num: 0,
ref_block_prefix: 0,
max_cpu_usage_ms: 0,
max_net_usage_words: 0,
delay_sec: 0,
})
default:
throw new Error('Invalid signing request data')
}
}
/** Whether the request is an identity request. */
public isIdentity(): boolean {
return this.data.req.variantName === 'identity'
}
/** Whether the request should be broadcast by signer. */
public shouldBroadcast(): boolean {
Iif (this.isIdentity()) {
return false
}
return this.data.flags.broadcast
}
/**
* Present if the request is an identity request and requests a specific account.
* @note This returns `nil` unless a specific identity has been requested,
* use `isIdentity` to check id requests.
*/
public getIdentity(): Name | null {
Iif (!this.isIdentity()) {
return null
}
const id = this.data.req.value as IdentityV2
Iif (id.permission && !id.permission.actor.equals(PlaceholderName)) {
return id.permission.actor
}
return null
}
/**
* Present if the request is an identity request and requests a specific permission.
* @note This returns `nil` unless a specific permission has been requested,
* use `isIdentity` to check id requests.
*/
public getIdentityPermission(): Name | null {
Iif (!this.isIdentity()) {
return null
}
const id = this.data.req.value as IdentityV2
Iif (id.permission && !id.permission.permission.equals(PlaceholderPermission)) {
return id.permission.permission
}
return null
}
/**
* Present if the request is an identity request and requests a specific permission.
* @note This returns `nil` unless a specific permission has been requested,
* use `isIdentity` to check id requests.
*/
public getIdentityScope(): Name | null {
Iif (!this.isIdentity() || this.version <= 2) {
return null
}
const id = this.data.req.value as IdentityV3
return id.scope
}
/** Get raw info dict */
public getRawInfo(): {[key: string]: Bytes} {
const rv: {[key: string]: Bytes} = {}
for (const {key, value} of this.data.info) {
rv[key] = value
}
return rv
}
public getRawInfoKey(key: string) {
const pair = this.data.info.find((pair) => pair.key === key)
if (pair) {
return pair.value
}
}
public setRawInfoKey(key: string, value: BytesType) {
let pair = this.data.info.find((pair) => pair.key === key)
if (!pair) {
pair = InfoPair.from({key, value})
this.data.info.push(pair)
} else E{
pair.value = Bytes.from(value)
}
}
/** Set a metadata key. */
public setInfoKey(key: string, object: ABISerializable, type?: ABISerializableType) {
let data: Bytes
Iif (typeof object === 'string' && !type) {
// match old behavior where strings encode to raw utf8 as opposed to
// eosio-abi encoded strings (varuint32 length prefix + utf8 bytes)
data = Bytes.from(object, 'utf8')
} else {
data = Serializer.encode({object, type})
}
this.setRawInfoKey(key, data)
}
/** Get a metadata key. */
public getInfoKey(key: string): string
public getInfoKey<T extends ABISerializableConstructor>(key: string, type: T): InstanceType<T>
public getInfoKey(key: string, type: ABISerializableType): any
public getInfoKey(key: string, type?: ABISerializableType): any {
const data = this.getRawInfoKey(key)
if (data) {
if (type) {
return Serializer.decode({data, type})
} else {
// assume utf8 string if no type is given
return data.utf8String
}
}
}
/** Return a deep copy of this request. */
public clone(): SigningRequest {
let signature: RequestSignature | undefined
Iif (this.signature) {
signature = RequestSignature.from(JSON.parse(JSON.stringify(this.signature)))
}
const RequestData = (this.constructor as typeof SigningRequest).storageType(this.version)
const data = RequestData.from(JSON.parse(JSON.stringify(this.data)))
return new SigningRequest(this.version, data, this.zlib, this.abiProvider, signature)
}
// Convenience methods.
public toString() {
return this.encode()
}
public toJSON() {
return this.encode()
}
}
export class ResolvedSigningRequest {
/** Recreate a resolved request from a callback payload. */
static async fromPayload(
payload: CallbackPayload,
options: SigningRequestEncodingOptions = {}
): Promise<ResolvedSigningRequest> {
const request = SigningRequest.from(payload.req, options)
const abis = await request.fetchAbis()
return request.resolve(
abis,
{actor: payload.sa, permission: payload.sp},
{
ref_block_num: payload.rbn,
ref_block_prefix: payload.rid,
expiration: payload.ex,
chainId: payload.cid || request.getChainId(),
}
)
}
/** The request that created the transaction. */
public readonly request: SigningRequest
/** Expected signer of transaction. */
public readonly signer: PermissionLevel
/** Transaction object with action data encoded. */
public readonly transaction: Transaction
/** Transaction object with action data decoded. */
public readonly resolvedTransaction: ResolvedTransaction
/** Id of chain where the request was resolved. */
public readonly chainId: ChainId
constructor(
request: SigningRequest,
signer: PermissionLevel,
transaction: Transaction,
resolvedTransaction: ResolvedTransaction,
chainId: ChainId
) {
this.request = request
this.signer = signer
this.transaction = transaction
this.resolvedTransaction = resolvedTransaction
this.chainId = chainId
}
public get serializedTransaction(): Uint8Array {
return Serializer.encode({object: this.transaction}).array
}
public get signingDigest(): Checksum256 {
return this.transaction.signingDigest(this.chainId)
}
public get signingData(): Bytes {
return this.transaction.signingData(this.chainId)
}
public getCallback(
signatures: SignatureType[],
blockNum?: UInt32Type
): ResolvedCallback | null {
const {callback, flags} = this.request.data
Iif (!callback || callback.length === 0) {
return null
}
Iif (!signatures || signatures.length === 0) {
throw new Error('Must have at least one signature to resolve callback')
}
const sigs = signatures.map((sig) => Signature.from(sig))
const payload: CallbackPayload = {
sig: String(sigs[0]),
tx: String(this.transaction.id),
rbn: String(this.transaction.ref_block_num),
rid: String(this.transaction.ref_block_prefix),
ex: String(this.transaction.expiration),
req: this.request.encode(),
sa: String(this.signer.actor),
sp: String(this.signer.permission),
cid: String(this.chainId),
}
for (const [n, sig] of sigs.slice(1).entries()) {
payload[`sig${n}`] = String(sig)
}
if (blockNum) {
payload.bn = String(UInt32.from(blockNum))
}
const url = callback.replace(/({{([a-z0-9]+)}})/g, (_1, _2, m) => {
return payload[m] || ''
})
return {
background: flags.background,
payload,
url,
}
}
public getIdentityProof(signature: SignatureType) {
Iif (!this.request.isIdentity()) {
throw new Error('Not a identity request')
}
return IdentityProof.from({
chainId: this.chainId,
scope: this.request.getIdentityScope()!,
expiration: this.transaction.expiration,
signer: this.signer,
signature,
})
}
}
function encodeAction(action: AnyAction, abis: Record<string, ABIDef>): Action {
if (Bytes.isBytes(action.data) || (action.data.constructor as any).abiName !== undefined) {
return Action.from(action)
}
const abi = abis[String(Name.from(action.account))]
Iif (!abi) {
throw new Error(`Missing ABI for ${action.account}`)
}
const data = Action.from(action, abi)
// TODO: The way payloads are encoded is including the ABI, which isn't what we want
// This needs to be resolved in wharfkit/antelope, and then the delete call here should be removed
delete data.abi
return data
}
function isIdentity(action: AnyAction) {
const account = Name.from(action.account)
const name = Name.from(action.name)
return account.rawValue.equals(0) && name.equals('identity')
}
function hasTapos(tx: Transaction) {
return !(tx.expiration.equals(0) && tx.ref_block_num.equals(0) && tx.ref_block_prefix.equals(0))
}
function expirationTime(timestamp?: TimePointType, expireSeconds: UInt32Type = 60) {
const ts = TimePointSec.from(timestamp || new Date())
const exp = UInt32.from(expireSeconds)
return TimePointSec.fromInteger(ts.value.adding(exp))
}
|