-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontract.js
More file actions
2413 lines (2184 loc) · 76.6 KB
/
contract.js
File metadata and controls
2413 lines (2184 loc) · 76.6 KB
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
(function () {
const OFFSET_SHORT_ITEM = 0x80;
const SIZE_THRESHOLD = 56;
const OFFSET_LONG_ITEM = 0xb7;
const OFFSET_SHORT_LIST = 0xc0;
const OFFSET_LONG_LIST = 0xf7;
const EMPTY_BYTES = new Uint8Array(new ArrayBuffer(0));
const EMPTY_RLP_ARRAY = new Uint8Array([0xc0])
const NULL_RLP = new Uint8Array([0x80])
const ENVS = {
NODE: 'NODE',
BROWSER: 'BROWSER'
}
const env = this['window'] === this ? ENVS.BROWSER : ENVS.NODE
const isBrowser = env === ENVS.BROWSER
const BN = require('./bn.js')
const _keccak256 = require('./sha3.js').keccak256
const nacl = require('./nacl.min.js')
const RMD160 = (new (require('./hashes.js').RMD160))
RMD160.setUTF8(false)
/**
* 比较两个字节数组
* @param {Uint8Array} a
* @param {Uint8Array} b
*/
function compareBytes(a, b) {
if (a.length > b.length)
return 1
if (b.length > a.length)
return -1
for (let i = 0; i < a.length; i++) {
const ai = a[i]
const bi = b[i]
if (ai > bi)
return 1
if (bi > ai)
return -1
}
return 0
}
// base58 编码
const base58 = base('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')
// rmd 不支持对 Uint8Array 进行哈希值计算,需要把 Uint8Array 类型伪装成字符串
class FakeString {
constructor(u8) {
this.u8 = u8
this.length = u8.length
}
charCodeAt(i) {
return this.u8[i]
}
}
/**
* rmd160 哈希值计算
* @param {Uint8Array} o
* @returns {Uint8Array}
*/
function rmd160(o) {
assert(isBytes(o), 'o is not byte array')
return decodeHex(RMD160.hex(new FakeString(o)))
}
/**
* base58 编码工具
* @param {string} ALPHABET
*/
function base(ALPHABET) {
var ALPHABET_MAP = {}
var BASE = ALPHABET.length
var LEADER = ALPHABET.charAt(0)
// pre-compute lookup table
for (var z = 0; z < ALPHABET.length; z++) {
var x = ALPHABET.charAt(z)
if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
ALPHABET_MAP[x] = z
}
/**
*
* @param {Uint8Array} source
*/
function encode(source) {
if (source.length === 0) return ''
var digits = [0]
for (var i = 0; i < source.length; ++i) {
for (var j = 0, carry = source[i]; j < digits.length; ++j) {
carry += digits[j] << 8
digits[j] = carry % BASE
carry = (carry / BASE) | 0
}
while (carry > 0) {
digits.push(carry % BASE)
carry = (carry / BASE) | 0
}
}
var string = ''
// deal with leading zeros
for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
// convert digits to a string
for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
return string
}
/**
*
* @param {string} string
* @returns {Uint8Array}
*/
function decodeUnsafe(string) {
if (typeof string !== 'string') throw new TypeError('Expected String')
if (string.length === 0) return new Uint8Array(0)
var bytes = [0]
for (var i = 0; i < string.length; i++) {
var value = ALPHABET_MAP[string[i]]
if (value === undefined)
throw new Error(`invalid char ${string[i]}`)
for (var j = 0, carry = value; j < bytes.length; ++j) {
carry += bytes[j] * BASE
bytes[j] = carry & 0xff
carry >>= 8
}
while (carry > 0) {
bytes.push(carry & 0xff)
carry >>= 8
}
}
// deal with leading zeros
for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
bytes.push(0)
}
return new Uint8Array(bytes.reverse())
}
function decode(string) {
var buffer = decodeUnsafe(string)
if (buffer) return buffer
throw new Error('Non-base' + BASE + ' character')
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
}
}
/**
* 私钥转公钥
* @param {Uint8Array | string | ArrayBuffer} privateKey
* @returns {Uint8Array}
*/
function privateKey2PublicKey(privateKey) {
privateKey = decodeHex(privateKey)
if (isBytes(privateKey))
privateKey = toU8Arr(privateKey)
if (privateKey.length === 64)
privateKey = privateKey.slice(32)
const pair = new nacl.sign.keyPair.fromSeed(privateKey)
return pair.publicKey
}
/**
* 公钥转公钥哈希
* @param {Uint8Array | string} publicKey
* @returns {Uint8Array}
*/
function publicKey2Hash(publicKey) {
publicKey = decodeHex(publicKey)
publicKey = digest(publicKey)
return rmd160(publicKey)
}
/**
* 地址转公钥哈希
*/
function address2PublicKeyHash(str) {
assert(typeof str === 'string', 'address is string')
let r5;
if (str.indexOf("1") == 0) {
r5 = base58.decode(str)
} else {
r5 = base58.decode(str.substr(2))
}
return r5.slice(1, r5.length - 4)
}
/**
* 公钥哈希转地址
* @param { Uint8Array } hash
*
*/
function publicKeyHash2Address(hash) {
let r2 = concatBytes(new Uint8Array([0]), hash)
let r3 = digest(digest(hash))
let b4 = r3.slice(0, 4)
let b5 = concatBytes(r2, b4)
return base58.encode(b5)
}
/**
* 32 字节私钥转成 64字节私钥
* @param {string} sk
*/
function extendPrivateKey(sk) {
sk = decodeHex(sk)
if (sk.length === 64)
return sk
return concatBytes(sk, privateKey2PublicKey(sk))
}
/**
* 断言正确的地址
* @param {string} address
*/
function assertAddress(address) {
if (!typeof address === 'string')
throw new Error('invalid address not a string')
if (!address.startsWith('1') && !address.startsWith('WX') && !address.startsWith('WR')) {
throw new Error('address should starts with 1, WX or WR')
}
if (address.startsWith('WX') || address.startsWith('WR'))
address = address.substr(2)
let _r5 = base58.decode(address);
let a = address2PublicKeyHash(address)
let c = digest(a)
let r3 = digest(c);
let b4 = r3.slice(0, 4)
let _b4 = _r5.slice(21, 25)
if (compareBytes(b4, _b4) != 0) {
throw new Error('invalid address ' + address)
}
}
/**
* 公钥、地址、或者公钥哈希 转成公钥哈希
* @param {string | Uint8Array | ArrayBuffer} 地址、公钥或者公钥哈希
* @returns {Uint8Array}
*/
function normalizeAddress(addr) {
if (typeof addr === 'string' && isHex(addr))
addr = decodeHex(addr)
if (isBytes(addr)) {
addr = toU8Arr(addr)
// 公要哈希 20 个字节
if (addr.length === 20)
return addr
// 32 字节的是公钥 转成公钥哈希
if (addr.length === 32)
return publicKey2Hash(addr)
throw new Error(`invalid size ${addr.length}`)
}
// 地址转公钥哈希
assertAddress(addr)
return address2PublicKeyHash(addr)
}
/**
* 计算 keccak256哈希
* @param {Uint8Array}
* @returns {Uint8Array}
*/
function digest(msg) {
assert(isBytes(msg), 'digest failed msg is not bytes')
const hasher = _keccak256.create()
hasher.update(msg)
return new Uint8Array(hasher.arrayBuffer())
}
// 事务的所有状态
const TX_STATUS = {
PENDING: 0,
INCLUDED: 1,
CONFIRMED: 2,
DROPPED: 3
}
function copy(dst, src) {
for (let key of Object.keys(src))
dst[key] = src[key]
}
/**
* 转成安全范围内的整数,如果不是安全范围内,用字符串表示
* @param {string | number | ArrayBuffer | Uint8Array | BN }
* @returns { string | number}
*/
function toSafeInt(x) {
if (typeof x === 'number')
return x
if (typeof x === 'string') {
const hex = x.startsWith('0x')
if (hex)
x = x.substr(2, x.length - 2)
x = new BN(x, hex ? 16 : 10)
}
if (x instanceof ArrayBuffer || x instanceof Uint8Array)
x = new BN(x, 'be')
if (x.cmp(MAX_SAFE_INTEGER) <= 0 && x.cmp(MIN_SAFE_INTEGER) >= 0)
return x.toNumber()
return x.toString()
}
const assert = this['assert'] ? this['assert'] : (truth, msg) => {
if (!truth)
throw new Error(msg || 'assert failed')
}
const MAX_U64 = new BN('ffffffffffffffff', 16);
const MAX_U256 = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16);
const MAX_I64 = new BN('9223372036854775807', 10);
const MIN_I64 = new BN('-9223372036854775808', 10);
const MAX_SAFE_INTEGER = new BN(Number.MAX_SAFE_INTEGER);
const MIN_SAFE_INTEGER = new BN(Number.MIN_SAFE_INTEGER);
const ONE = new BN(1)
/**
* 截掉字节数组前面的 0
* @param { Uint8Array | ArrayBuffer } data 字节数组
*/
function trimLeadingZeros(data) {
assert(isBytes(data), 'data is not bytes')
data = toU8Arr(data)
let k = -1;
for (let i = 0; i < data.length; i++) {
if (data[i] !== 0) {
k = i;
break;
}
}
if (k === -1)
return new Uint8Array(0)
return data.slice(k, data.length)
}
function hexToInt(x) {
if (48 <= x && x <= 57) return x - 48;
if (97 <= x && x <= 102) return x - 87;
if (65 <= x && x <= 70) return x - 55;
return 0;
}
/**
* 解析十六进制字符串
* decode hex string
* @param {string | ArrayBuffer | Uint8Array} s
* @returns {Uint8Array}
*/
function decodeHex(s) {
if (isBytes(s))
return toU8Arr(s)
if (s.startsWith('0x'))
s = s.substr(2, s.length - 2)
assert(s.length % 2 === 0, 'invalid char');
const ret = new Uint8Array(s.length / 2);
for (let i = 0; i < s.length / 2; i++) {
const h = s.charCodeAt(i * 2);
const l = s.charCodeAt(i * 2 + 1);
ret[i] = (hexToInt(h) << 4) + hexToInt(l);
}
return ret;
}
/**
* 判断是否是合法的十六进制字符串
* @param {string} hex
* @returns {boolean}
*/
function isHex(hex) {
if (typeof hex === 'string' && hex.startsWith('0x'))
hex = hex.substr(2)
if (hex.length % 2 !== 0)
return false
hex = hex.toLowerCase()
for (let i = 0; i < hex.length; i++) {
const code = hex.charCodeAt(i)
if ((code >= 48 && code <= 57) || (code >= 97 && code <= 102)) {
} else {
return false
}
}
return true
}
/**
* convert bytes like objects to hex string 十六进制编码
* @param {string | ArrayBuffer | Uint8Array } s
* @returns {string}
*/
function bin2hex(s) {
if (typeof s === 'string' && s.startsWith('0x')) {
s = s.substr(2)
}
if (typeof s === 'string') {
assert(isHex(s), `invalid hex string ${s}`)
}
if (isBytes(s))
return encodeHex(s)
return s
}
/**
* convert digital like objects to digital string 转成十进制表示的字符串
* @param {string | BN | number } s
* @returns {string}
*/
function asDigitalNumberText(s) {
if (typeof s === 'string') {
if (s.startsWith('0x'))
s = new BN(s.substr(2), 16)
else
return s
}
return s.toString(10)
}
class TypeDef {
/**
*
* @param {string} type
* @param {string} name
*/
constructor(type, name) {
type = type && type.toLowerCase()
assert(
type === ABI_DATA_TYPE.STRING
|| type === ABI_DATA_TYPE.U64
|| type === ABI_DATA_TYPE.ADDRESS
|| type === ABI_DATA_TYPE.BYTES
|| type === ABI_DATA_TYPE.U256
|| type === ABI_DATA_TYPE.BOOL
|| type === ABI_DATA_TYPE.I64
|| type === ABI_DATA_TYPE.F64,
`invalid abi type def name = ${name} type = ${type}`
)
this.type = type
this.name = name
}
/**
*
* @param {Object} o
* @return {TypeDef}
*/
static from(o) {
return new TypeDef(o.type, o.name)
}
}
class ABI {
/**
*
* @param {string} name
* @param {string} type
* @param {Array<TypeDef> } inputs
* @param {Array<TypeDef>} outputs
*/
constructor(name, type, inputs, outputs) {
type = type && type.toLowerCase()
assert(name, 'expect name of abi')
assert(type === ABI_TYPE.FUNCTION || type === ABI_TYPE.EVENT, `invalid abi type ${type}`)
assert(!inputs || Array.isArray(inputs), `invalid inputs ${inputs}`)
assert(!outputs || Array.isArray(outputs), `invalid inputs ${outputs}`)
this.name = name
this.type = type
this.inputs = (inputs || []).map(TypeDef.from)
this.outputs = (outputs || []).map(TypeDef.from)
}
static from(o) {
return new ABI(o.name, o.type, o.inputs, o.outputs)
}
returnsObj() {
return this.outputs.every(v => v.name) && (
(new Set(this.outputs.map(v => v.name))).size === this.outputs.length
)
}
inputsObj() {
return this.inputs.every(v => v.name) && (
(new Set(this.inputs.map(v => v.name))).size === this.inputs.length
)
}
toObj(arr, input) {
const p = input ? this.inputs : this.outputs
const o = {}
for (let i = 0; i < p.length; i++) {
o[p[i].name] = arr[i]
}
return o
}
toArr(obj, input) {
const p = input ? this.inputs : this.outputs
const arr = []
for (let i = 0; i < p.length; i++) {
arr.push(obj[p[i].name])
}
return arr
}
}
function normalizeParams(params) {
if (params === null || params === undefined)
return []
if (typeof params === 'string' || typeof params === 'boolean' || typeof params === 'number' || params instanceof ArrayBuffer || params instanceof Uint8Array || params instanceof BN)
return [params]
return params
}
/**
* abi 解码
* @param {Array<TypeDef>} outputs
* @param {string | ArrayBuffer | Array<Uint8Array> | Uint8Array} buf
*/
function abiDecode(outputs, buf) {
if (!buf)
buf = ''
if (typeof buf === 'string')
buf = decodeHex(buf)
if (buf.length === 0)
return []
const arr = Array.isArray(buf) ? buf : RLP.decode(buf)
const returnObject =
outputs.every(v => v.name) && (
(new Set(outputs.map(v => v.name))).size === outputs.length
)
if (arr.length != outputs.length)
throw new Error(`abi decode failed , expect ${outputs.length} returns while ${arr.length} found`)
const ret = returnObject ? {} : []
for (let i = 0; i < arr.length; i++) {
const t = outputs[i].type
const name = outputs[i].name
let val
switch (t) {
case ABI_DATA_TYPE.BYTES:
val = encodeHex(arr[i])
break
case ABI_DATA_TYPE.ADDRESS:
val = publicKeyHash2Address(arr[i])
break
case ABI_DATA_TYPE.U256:
case ABI_DATA_TYPE.U64: {
val = new BN(arr[i], 'be')
if (t === ABI_DATA_TYPE.U64)
assert(val.cmp(MAX_U64) <= 0, `${val.toString(10)} overflows max u64 ${MAX_U64.toString(10)}`)
if (t === ABI_DATA_TYPE.U256)
assert(val.cmp(MAX_U256) <= 0, `${val.toString(10)} overflows max u256 ${MAX_U256.toString(10)}`)
val = toSafeInt(val)
break
}
case ABI_DATA_TYPE.I64: {
const padded = padPrefix(arr[i], 0, 8)
const isneg = padded[0] & 0x80;
if (!isneg) {
val = new BN(arr[i], 'be')
} else {
val = new BN(inverse(padded), 'be')
val = val.add(ONE)
val = val.neg()
}
val = toSafeInt(val)
break
}
case ABI_DATA_TYPE.F64: {
val = bytesToF64(arr[i])
break
}
case ABI_DATA_TYPE.STRING: {
val = bin2str(arr[i])
break
}
case ABI_DATA_TYPE.BOOL: {
val = arr[i].length > 0
break
}
}
if (returnObject)
ret[name] = val
else
ret[i] = val
}
return ret
}
/**
* 事务
*/
class Transaction {
/**
* constructor of transaction
* @param {string | number | BN} [version]
* @param {string | number | BN} [type]
* @param {string | number | BN} [nonce]
* @param {string | Uint8Array | ArrayBuffer} [from]
* @param {string | number | BN} [gasPrice]
* @param {string | number | BN} [amount]
* @param {string | Uint8Array | ArrayBuffer } [payload]
* @param {string | Uint8Array | ArrayBuffer} [to]
* @param {string | Uint8Array | ArrayBuffer } [signature]
* @param { Array<ABI> } [__abi] abi
* @param { Array | Object } [__inputs] inputs
*/
constructor(version, type, nonce, from, gasPrice, amount, payload, to, signature, __abi, __inputs) {
this.version = asDigitalNumberText(version || 0)
this.type = asDigitalNumberText(type || 0)
this.nonce = asDigitalNumberText(nonce || 0)
this.from = bin2hex(from || '')
this.gasPrice = asDigitalNumberText(gasPrice || 0)
this.amount = asDigitalNumberText(amount || 0)
this.payload = bin2hex(payload || '')
this.to = bin2hex(to || '')
this.signature = bin2hex(signature || '')
this.__abi = __abi
this.__inputs = __inputs
}
static clone(o) {
return new Transaction(o.version, o.type, o.nonce, o.from, o.gasPrice, o.amount, o.payload, o.to, o.signature)
}
/**
* 计算事务哈希值
* @returns { Uint8Array } 哈希值
*/
getHash() {
return digest(this.getRaw(false))
}
/**
* 生成事务签名或者哈希值计算需要的原文
* @param {boolean} nullSig
* @returns {Uint8Array}
*/
getRaw(nullSig) {
let sig = nullSig ? new Uint8Array(64) : decodeHex(this.signature)
const p = decodeHex(this.payload)
return concatBytes(
[
new Uint8Array([parseInt(this.version)]),
new Uint8Array([parseInt(this.type)]),
padPrefix((new BN(this.nonce)).toArrayLike(Uint8Array, 'be'), 0, 8),
decodeHex(this.from),
padPrefix((new BN(this.gasPrice)).toArrayLike(Uint8Array, 'be'), 0, 8),
padPrefix((new BN(this.amount)).toArrayLike(Uint8Array, 'be'), 0, 8),
sig,
decodeHex(this.to),
padPrefix((new BN(p.length)).toArrayLike(Uint8Array, 'be'), 0, 4),
p
]
)
}
/**
* rlp 编码结果
* @returns { Uint8Array }
*/
getEncoded() {
const arr = this.__toArr()
return RLP.encode(arr)
}
__toArr() {
return [
convert(this.version || 0, ABI_DATA_TYPE.U64),
convert(this.type || 0, ABI_DATA_TYPE.U64),
convert(this.nonce || '0', ABI_DATA_TYPE.U64),
convert(this.from || EMPTY_BYTES, ABI_DATA_TYPE.BYTES),
convert(this.gasPrice || '0', ABI_DATA_TYPE.U256),
convert(this.amount || '0', ABI_DATA_TYPE.U256),
convert(this.payload || EMPTY_BYTES, ABI_DATA_TYPE.BYTES),
decodeHex(this.to),
convert(this.signature || EMPTY_BYTES, ABI_DATA_TYPE.BYTES)
]
}
/**
* 签名
* @param {string | Uint8Array | ArrayBuffer } sk 私钥
*/
sign(sk) {
sk = decodeHex(sk)
sk = extendPrivateKey(sk)
this.signature = encodeHex(nacl.sign(this.getRaw(true), sk).slice(0, 64))
}
__setInputs(__inputs) {
const cnv = (x) => {
if (x instanceof ArrayBuffer || x instanceof Uint8Array)
return encodeHex(x)
if (x instanceof BN)
return toSafeInt(x)
return x
}
if (Array.isArray(__inputs)) {
this.__inputs = __inputs.map(cnv)
} else {
this.__inputs = {}
for (let k of Object.keys(__inputs)) {
this.__inputs[k] = cnv(__inputs[k])
}
}
if (Array.isArray(this.__inputs)) {
const c = new Contract('', this.__abi)
const a = c.getABI(this.getMethod(), ABI_TYPE.FUNCTION)
if (a.inputsObj()) {
this.__inputs = a.toObj(this.__inputs, true)
}
}
}
getMethod() {
const t = parseInt(this.type)
return t === constants.WASM_DEPLOY ? 'init' : bin2str((RLP.decode(decodeHex(this.payload)))[1])
}
isDeployOrCall() {
const t = parseInt(this.type)
return t === constants.WASM_DEPLOY || t === constants.WASM_CALL
}
static fromRPCBytes(x){
return Transaction.fromRaw(x, true)
}
static fromRaw(x, hash) {
var args = []
var offset = 0
var shift = function (n) {
offset = offset + n
return offset
}
var u8 = decodeHex(x)
// version
args.push(u8[offset++])
if(hash)
offset += 32
// type
args.push(u8[offset++])
// nonce
args.push(new BN(u8.slice(offset, shift(8)), 'hex', 'be'))
// from
args.push(u8.slice(offset, shift(32)))
// gasprice
args.push(new BN(u8.slice(offset, shift(8)), 'hex', 'be'))
// amount
args.push(new BN(u8.slice(offset, shift(8)), 'hex', 'be'))
// signature
var sig = u8.slice(offset, shift(64))
// to
var to = u8.slice(offset, shift(20))
// payload length
var len = (new BN(u8.slice(offset, shift(4)), 'hex', 'be')).toNumber()
// payload
var p = u8.slice(offset, shift(len))
args.push(p, to, sig);
return new Transaction(
args[0],
args[1],
args[2],
args[3],
args[4],
args[5],
p,
to,
sig
)
}
}
/**
* 判断是否是二进制字节数组
* @param s
* @returns {boolean}
*/
function isBytes(s) {
return s instanceof Uint8Array || s instanceof ArrayBuffer
}
/**
* convert uint8array or array buffer to uint8 array
* @param {Uint8Array | ArrayBuffer} data
* @returns {Uint8Array}
*/
function toU8Arr(data) {
assert(isBytes(data), `${data} is not uint8array or arraybuffer`)
if (data instanceof ArrayBuffer)
return new Uint8Array(data)
return data
}
/**
* 字节数组转 number
* @param {Uint8Array | ArrayBuffer} bytes
* @returns {number}
*/
function byteArrayToInt(bytes) {
bytes = toU8Arr(bytes)
let ret = 0;
for (let i = 0; i < bytes.length; i++) {
const u = bytes[bytes.length - i - 1];
ret += (u << (i * 8))
}
return ret;
}
/**
* 十六进制字符串编码
* @param { ArrayBuffer | Uint8Array } buf binary
* @returns {string} encoded result
*/
function encodeHex(buf) {
buf = toU8Arr(buf)
let out = "";
for (let i = 0; i < buf.length; i++) {
let n = buf[i].toString(16)
if (n.length === 1)
n = '0' + n
out += n
}
return out;
}
/**
* decode binary as utf8 string
* @param { Uint8Array | ArrayBuffer } bin
* @returns {string} decoded result
*/
function bin2str(bin) {
bin = toU8Arr(bin)
if (isBrowser)
return new TextDecoder().decode(bin)
return Buffer.from(bin).toString('utf8')
}
/**
* convert string to binary
* @param { string } str
* @returns {Uint8Array}
*/
function str2bin(str) {
if (isBrowser)
return new TextEncoder().encode(str)
return Buffer.from(str, 'utf8')
}
/**
* pad prefix to size
* @param { Uint8Array } arr
* @param {number} prefix
* @param {number} size
*/
function padPrefix(arr, prefix, size) {
if (arr.length >= size)
return arr
const ret = new Uint8Array(size)
for (let i = 0; i < ret.length; i++) {
ret[i + size - arr.length] = arr[i]
}
if (prefix === 0)
return ret
for (let i = 0; i < size - arr.length; i++)
ret[i] = prefix
}
/**
* number 转字节数组
* @param {number} u
* @returns {Uint8Array}
*/
function numberToByteArray(u) {
if (u < 0 || !Number.isInteger(u))
throw new Error(`cannot convert number ${u} to byte array`)
const buf = new Uint8Array(8);
for (let i = 0; i < 8; i++) {
buf[buf.length - 1 - i] = u & 0xff;
u = u >>> 8;
}
let k = 8;
for (let i = 0; i < 8; i++) {
if (buf[i] !== 0) {
k = i;
break;
}
}
return buf.slice(k, buf.length);
}
function reverse(arr) {
const ret = new Uint8Array(arr.length)
for (let i = 0; i < arr.length; i++) {
ret[i] = arr[arr.length - i - 1]
}
return ret
}
/**
* 浮点数转字节数组
* @param {Uint8Array} arr
*/
function f64ToBytes(f) {
let buf = new ArrayBuffer(8);
let float = new Float64Array(buf);
float[0] = f;
buf = new Uint8Array(buf)
return trimLeadingZeros(reverse(buf))
}
/**
* 字节数组转浮点数
* @param {Uint8Array} buf
*/
function bytesToF64(buf) {
return new Float64Array(padPrefix(reverse(buf), 0, 8).buffer)[0]
}
/**
* 对字节数组取反
* @param {Uint8Array} arr
*/
function inverse(arr) {
const ret = new Uint8Array(arr.length)
for (let i = 0; i < ret.length; i++) {
ret[i] = (~arr[i] & 0xff)
}
return ret
}
function isRLPList(encoded) {
return encoded[0] >= OFFSET_SHORT_LIST;
}
/**
* encode bytes to rlp
* @param { ArrayBuffer | Uint8Array } bytes
* @returns { Uint8Array }
*/
function encodeBytes(bytes) {
if (bytes instanceof ArrayBuffer)
bytes = new Uint8Array(bytes)
if (bytes.length === 0) {
const ret = new Uint8Array(1);
ret[0] = OFFSET_SHORT_ITEM;
return ret;
}
if (bytes.length === 1 && (bytes[0] & 0xFF) < OFFSET_SHORT_ITEM) {
return bytes;
}
if (bytes.length < SIZE_THRESHOLD) {
// length = 8X
const prefix = OFFSET_SHORT_ITEM + bytes.length;
const ret = new Uint8Array(bytes.length + 1);
for (let i = 0; i < bytes.length; i++) {
ret[i + 1] = bytes[i];
}
ret[0] = prefix;
return ret;
}
let tmpLength = bytes.length;