This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.js
1954 lines (1664 loc) · 68.7 KB
/
index.js
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
/*
Modifications copyright 2018 The caver-js Authors
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
This file is derived from web3.js/packages/web3-eth-accounts/src/index.js (2019/06/12).
Modified and improved for the caver-js development.
*/
/**
* @file accounts.js
* @author Fabian Vogelsteller <fabian@ethereum.org>
* @date 2017
*/
const _ = require('lodash')
const Promise = require('any-promise')
// account, hash, rlp, nat, bytes library will be used from 'eth-lib' temporarily.
const AccountLib = require('eth-lib/lib/account')
const Hash = require('eth-lib/lib/hash')
const RLP = require('eth-lib/lib/rlp')
const Nat = require('eth-lib/lib/nat')
const Bytes = require('eth-lib/lib/bytes')
const cryp = typeof global === 'undefined' ? require('crypto-browserify') : require('crypto')
const uuid = require('uuid')
const elliptic = require('elliptic')
const scrypt = require('./scrypt')
const utils = require('../../../caver-utils')
const helpers = require('../../../caver-core-helpers')
const Method = require('../../../caver-core-method')
const core = require('../../../caver-core')
const {
encodeRLPByTxType,
makeRawTransaction,
getSenderTxHash,
decodeFromRawTransaction,
splitFeePayer,
extractSignatures,
} = require('./makeRawTransaction')
const secp256k1 = new elliptic.ec('secp256k1')
const AccountKeyPublic = require('./accountKey/accountKeyPublic')
const AccountKeyMultiSig = require('./accountKey/accountKeyMultiSig')
const AccountKeyRoleBased = require('./accountKey/accountKeyRoleBased')
const { AccountKeyEnum } = require('./accountKey/accountKeyEnum')
const Account = require('./account/account')
const AccountForUpdate = require('./account/accountForUpdate')
const { rpc } = require('../../../caver-rtm')
const isNot = function(value) {
return _.isUndefined(value) || _.isNull(value)
}
function coverInitialTxValue(tx) {
if (typeof tx !== 'object') throw new Error('Invalid transaction')
if (!tx.senderRawTransaction && (!tx.type || tx.type === 'LEGACY' || tx.type.includes('SMART_CONTRACT_DEPLOY'))) {
tx.to = tx.to || '0x'
tx.data = utils.addHexPrefix(tx.data || '0x')
}
tx.chainId = utils.numberToHex(tx.chainId)
return tx
}
/**
* resolveArgsForSignTransaction parse arguments for signTransaction.
*
* @method resolveArgsForSignTransaction
* @param {Object} args Parameters of signTransaction.
* @return {Object}
*/
function resolveArgsForSignTransaction(args) {
if (args.length === 0 || args.length > 3) {
throw new Error('Invalid parameter: The number of parameters is invalid.')
}
// privateKey and callback are optional parameter
// "args.length === 2" means that user sent parameter privateKey or callback
const tx = args[0]
let privateKey
let callback
if (!tx || (!_.isObject(tx) && !_.isString(tx))) {
throw new Error('Invalid parameter: The transaction must be defined as an object or RLP encoded string')
}
if (args.length === 2) {
if (_.isFunction(args[1])) {
callback = args[1]
} else {
privateKey = args[1]
}
} else if (args.length === 3) {
if (args[1] && typeof args[1] !== 'string' && !_.isArray(args[1])) {
throw new Error('Invalid parameter: The parameter for the private key is invalid')
}
privateKey = args[1]
callback = args[2]
}
// For handling when callback is undefined.
callback = callback || function() {}
return { tx, privateKey, callback }
}
/**
* resolveArgsForFeePayerSignTransaction parse arguments for feePayerSignTransaction.
*
* @method resolveArgsForFeePayerSignTransaction
* @param {Object} args Parameters of feePayerSignTransaction.
* @return {Object}
*/
function resolveArgsForFeePayerSignTransaction(args) {
if (args.length === 0 || args.length > 4) {
throw new Error('Invalid parameter: The number of parameters is invalid.')
}
// privateKey and callback are optional parameter
// "args.length === 3" means that user sent parameter privateKey or callback
const tx = args[0]
const feePayer = args[1]
let privateKey
let callback
if (!tx || (!_.isObject(tx) && !_.isString(tx))) {
throw new Error('Invalid parameter: The transaction must be defined as an object or RLP encoded string')
}
if (!utils.isAddress(feePayer)) {
throw new Error(`Invalid fee payer address : ${feePayer}`)
}
if (args.length === 3) {
if (_.isFunction(args[2])) {
callback = args[2]
} else {
privateKey = args[2]
}
} else if (args.length === 4) {
if (args[2] && typeof args[2] !== 'string' && !_.isArray(args[2])) {
throw new Error('Invalid parameter: The parameter for the private key is invalid')
}
privateKey = args[2]
callback = args[3]
}
// For handling when callback is undefined.
callback = callback || function() {}
return { tx, privateKey, feePayer, callback }
}
const Accounts = function Accounts(...args) {
const _this = this
// sets _requestmanager
core.packageInit(this, args)
// remove unecessary core functions
delete this.BatchRequest
delete this.extend
const _klaytnCall = [rpc.getChainId, rpc.getGasPrice, rpc.getTransactionCount]
// attach methods to this._klaytnCall
this._klaytnCall = {}
_.each(_klaytnCall, function(method) {
method = new Method(method)
method.attachToObject(_this._klaytnCall)
method.setRequestManager(_this._requestManager)
})
this.wallet = new Wallet(this)
}
Accounts.prototype._addAccountFunctions = function(account) {
const _this = this
// add sign functions
account.signTransaction = function signTransaction(tx, callback) {
const roleKey = _this._getRoleKey(tx, account)
return _this.signTransaction(tx, roleKey, callback)
}
account.feePayerSignTransaction = function feePayerSignTransaction(tx, callback) {
return _this.feePayerSignTransaction(tx, account.address, account.feePayerKey, callback)
}
account.sign = function sign(data) {
return _this.sign(data, account.privateKey)
}
account.encrypt = function encrypt(password, options = {}) {
options.address = account.address
return _this.encrypt(account.keys, password, options)
}
account.getKlaytnWalletKey = function getKlaytnWalletKey() {
return genKlaytnWalletKeyStringFromAccount(account)
}
return account
}
/**
* _determineAddress determines the priority of the parameters entered and returns the address that should be used for the account.
*
* @method _determineAddress
* @param {Object} legacyAccount Account with a legacy account key extracted from private key to be used for address determination.
* @param {String} addressFromKey Address extracted from key.
* @param {String} userInputAddress Address passed as parameter by user.
* @return {String}
*/
Accounts.prototype._determineAddress = function _determineAddress(legacyAccount, addressFromKey, userInputAddress) {
if (userInputAddress) {
if (addressFromKey && addressFromKey !== userInputAddress) {
throw new Error('The address extracted from the private key does not match the address received as the input value.')
}
if (!utils.isAddress(userInputAddress)) {
throw new Error('The address received as the input value is invalid.')
}
return userInputAddress
}
if (addressFromKey) {
if (!utils.isAddress(addressFromKey)) {
throw new Error('The address extracted from the private key is invalid.')
}
// If userInputAddress is undefined and address which is came from private is existed, set address in account.
return addressFromKey
}
return legacyAccount.address
}
/**
* _getRoleKey returns a key that matches the role that should be used according to the transaction.
*
* @method _getRoleKey
* @param {Object} tx transaction object to be sign.
* @param {Object} account Account to be used for signing.
* @return {String|Array}
*/
Accounts.prototype._getRoleKey = function _getRoleKey(tx, account) {
let key
if (!account) {
throw new Error('The account to be used for signing is not defined.')
}
if (tx.senderRawTransaction && tx.feePayer) {
key = account.feePayerKey
} else if (tx.type && tx.type.includes('ACCOUNT_UPDATE')) {
key = account.updateKey
} else {
key = account.transactionKey
}
if (!key) {
throw new Error('The key corresponding to the role used for signing is not defined.')
}
return key
}
/**
* create function creates random account with entropy.
*
* @method create
* @param {Object} entropy A random string to increase entropy.
* @return {Object}
*/
Accounts.prototype.create = function create(entropy) {
return this._addAccountFunctions(Account.fromObject(AccountLib.create(entropy || utils.randomHex(32))))
}
/**
* createAccountKey creates AccountKeyPublic, AccountKeyMultiSig or AccountKeyRoleBased instance with parameter.
*
* @method createAccountKey
* @param {String|Array|Object} accountKey Parameters to be used when creating the AccountKey.
* @return {Object}
*/
Accounts.prototype.createAccountKey = function createAccountKey(accountKey) {
if (Account.isAccountKey(accountKey)) accountKey = accountKey.keys
if (_.isString(accountKey)) {
accountKey = this.createAccountKeyPublic(accountKey)
} else if (_.isArray(accountKey)) {
accountKey = this.createAccountKeyMultiSig(accountKey)
} else if (_.isObject(accountKey)) {
accountKey = this.createAccountKeyRoleBased(accountKey)
} else {
throw new Error(`Invalid accountKey type: ${typeof accountKey}`)
}
return accountKey
}
/**
* createAccountKeyPublic creates AccountKeyPublic with a string of private key.
*
* @method createAccountKeyPublic
* @param {String} privateKey Private key string that will be used to create AccountKeyPublic.
* @return {Object}
*/
Accounts.prototype.createAccountKeyPublic = function createAccountKeyPublic(privateKey) {
if (privateKey instanceof AccountKeyPublic) return privateKey
if (!_.isString(privateKey)) {
throw new Error('Creating a AccountKeyPublic requires a private key string.')
}
const parsed = utils.parsePrivateKey(privateKey)
privateKey = parsed.privateKey
if (!utils.isValidPrivateKey(privateKey)) {
throw new Error(`Failed to create AccountKeyPublic. Invalid private key : ${privateKey}`)
}
return new AccountKeyPublic(privateKey)
}
/**
* createAccountKeyMultiSig creates AccountKeyMultiSig with an array of private keys.
*
* @method createAccountKeyMultiSig
* @param {Array} privateKeys An Array of private key strings that will be used to create AccountKeyMultiSig.
* @return {Object}
*/
Accounts.prototype.createAccountKeyMultiSig = function createAccountKeyMultiSig(privateKeys) {
if (privateKeys instanceof AccountKeyMultiSig) return privateKeys
if (!_.isArray(privateKeys)) {
throw new Error('Creating a AccountKeyMultiSig requires an array of private key string.')
}
for (let i = 0; i < privateKeys.length; i++) {
const parsed = utils.parsePrivateKey(privateKeys[i])
const p = parsed.privateKey
if (!utils.isValidPrivateKey(p)) {
throw new Error(`Failed to create AccountKeyMultiSig. Invalid private key : ${p}`)
}
}
return new AccountKeyMultiSig(privateKeys)
}
/**
* createAccountKeyRoleBased creates AccountKeyRoleBased with an obejct of key.
*
* @method createAccountKeyRoleBased
* @param {Object} keyObject Object that defines key for each role to use when creating AccountKeyRoleBased.
* @return {Object}
*/
Accounts.prototype.createAccountKeyRoleBased = function createAccountKeyRoleBased(keyObject) {
if (keyObject instanceof AccountKeyRoleBased) return keyObject
if (!_.isObject(keyObject) || _.isArray(keyObject)) {
throw new Error('Creating a AccountKeyRoleBased requires an object.')
}
return new AccountKeyRoleBased(keyObject)
}
/**
* accountKeyToPublicKey creates public key format with AccountKey.
*
* @method accountKeyToPublicKey
* @param {Object} accountKey AccountKey instance for which you want to generate a public key format.
* @return {String|Array|Object}
*/
Accounts.prototype.accountKeyToPublicKey = function accountKeyToPublicKey(accountKey) {
accountKey = this.createAccountKey(accountKey)
return accountKey.toPublicKey(this.privateKeyToPublicKey)
}
/**
* createWithAccountKey creates Account instance with AccountKey.
*
* @method createWithAccountKey
* @param {String} address The address of account.
* @param {String|Array|Object} accountKey The accountKey of account.
* @return {Object}
*/
Accounts.prototype.createWithAccountKey = function createWithAccountKey(address, accountKey) {
const account = new Account(address, this.createAccountKey(accountKey))
return this._addAccountFunctions(account)
}
/**
* createWithAccountKeyPublic create an account with AccountKeyPublic.
*
* @method createWithAccountKeyPublic
* @param {String} address An address of account.
* @param {String|Object} key Key of account.
* @return {Object}
*/
Accounts.prototype.createWithAccountKeyPublic = function createWithAccountKeyPublic(address, key) {
if (!Account.isAccountKey(key)) key = this.createAccountKeyPublic(key)
if (key.type !== AccountKeyEnum.ACCOUNT_KEY_PUBLIC) {
throw new Error(`Failed to create account with AccountKeyPublic. Invalid account key : ${key.type}`)
}
const account = new Account(address, key)
return this._addAccountFunctions(account)
}
/**
* createWithAccountKeyMultiSig create an account with AccountKeyMultiSig.
*
* @method createWithAccountKeyMultiSig
* @param {String} address An address of account.
* @param {String|Object} keys Key of account.
* @return {Object}
*/
Accounts.prototype.createWithAccountKeyMultiSig = function createWithAccountKeyMultiSig(address, keys) {
if (!Account.isAccountKey(keys)) keys = this.createAccountKeyMultiSig(keys)
if (keys.type !== AccountKeyEnum.ACCOUNT_KEY_MULTISIG) {
throw new Error(`Failed to create account with AccountKeyMultiSig. Invalid account key : ${keys.type}`)
}
const account = new Account(address, keys)
return this._addAccountFunctions(account)
}
/**
* createWithAccountKeyRoleBased create an account with AccountKeyRoleBased.
*
* @method createWithAccountKeyRoleBased
* @param {String} address An address of account.
* @param {String|Object} keyObject Key of account.
* @return {Object}
*/
Accounts.prototype.createWithAccountKeyRoleBased = function createWithAccountKeyRoleBased(address, keyObject) {
if (!Account.isAccountKey(keyObject)) {
keyObject = this.createAccountKeyRoleBased(keyObject)
}
if (keyObject.type !== AccountKeyEnum.ACCOUNT_KEY_ROLEBASED) {
throw new Error(`Failed to create account with AccountKeyRoleBased. Invalid account key : ${keyObject.type}`)
}
const account = new Account(address, keyObject)
return this._addAccountFunctions(account)
}
/**
* privateKeyToAccount creates and returns an Account through the input passed as parameters.
*
* @method privateKeyToAccount
* @param {String} key The key parameter can be either normal private key or KlaytnWalletKey format.
* @param {String} userInputAddress The address entered by the user for use in creating an account.
* @return {Object}
*/
Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(key, userInputAddress) {
const { legacyAccount: account, klaytnWalletKeyAddress } = this.getLegacyAccount(key)
account.address = this._determineAddress(account, klaytnWalletKeyAddress, userInputAddress)
account.address = account.address.toLowerCase()
account.address = utils.addHexPrefix(account.address)
return account
}
/**
* createAccountForUpdate creates an AccountForUpdate instance.
* The AccountForUpdate returned as a result of this function contains only the address and public key used to update the account.
*
* @method createAccountForUpdate
* @param {String} address The address value of AccountForUpdate, a structure that contains data for updating an account.
* @param {String|Array|Object} accountKey Private key or AccountKey to update account.
* @param {Object} options Options to use for setting threshold and weight for multiSig.
* @return {Object}
*/
Accounts.prototype.createAccountForUpdate = function createAccountForUpdate(address, accountKey, options) {
let legacyOrFail
// Logic for handling cases where legacyKey or failKey is set inside AccountKeyRoleBased object.
if (!_.isArray(accountKey) && _.isObject(accountKey)) {
legacyOrFail = {}
Object.keys(accountKey).map(role => {
if (accountKey[role] === 'legacyKey' || accountKey[role] === 'failKey') {
legacyOrFail[role] = accountKey[role]
delete accountKey[role]
}
})
if (Object.keys(accountKey).length === 0) {
return new AccountForUpdate(address, legacyOrFail, options)
}
}
const publicKey = this.accountKeyToPublicKey(accountKey)
if (legacyOrFail !== undefined) {
Object.assign(publicKey, legacyOrFail)
}
return new AccountForUpdate(address, publicKey, options)
}
/**
* createAccountForUpdateWithPublicKey creates AccountForUpdate instance with public key format.
*
* @method createAccountForUpdateWithPublicKey
* @param {String} address The address value of AccountForUpdate, a structure that contains data for updating an account.
* @param {String|Array|Object} keyForUpdate Public key to update.
* @param {Object} options Options to use for setting threshold and weight for multiSig.
* @return {Object}
*/
Accounts.prototype.createAccountForUpdateWithPublicKey = function createAccountForUpdateWithPublicKey(address, keyForUpdate, options) {
return new AccountForUpdate(address, keyForUpdate, options)
}
/**
* createAccountForUpdateWithLegacyKey creates AccountForUpdate instance with legacyKey.
*
* @method createAccountForUpdateWithLegacyKey
* @param {String} address The address of account to update with the legacy key.
* @return {Object}
*/
Accounts.prototype.createAccountForUpdateWithLegacyKey = function createAccountForUpdateWithLegacyKey(address) {
return new AccountForUpdate(address, 'legacyKey')
}
/**
* createAccountForUpdateWithFailKey creates AccountForUpdate instance with failKey.
*
* @method createAccountForUpdateWithFailKey
* @param {String} address The address of account to update with the fail key.
* @return {Object}
*/
Accounts.prototype.createAccountForUpdateWithFailKey = function createAccountForUpdateWithFailKey(address) {
return new AccountForUpdate(address, 'failKey')
}
/**
* isDecoupled determines whether or not it is decoupled based on the input value.
*
* @method isDecoupled
* @param {String} key The key parameter can be either normal private key or KlaytnWalletKey format.
* @param {String} userInputAddress The address to use when determining whether it is decoupled.
* @return {Boolean}
*/
Accounts.prototype.isDecoupled = function isDecoupled(key, userInputAddress) {
const { legacyAccount, klaytnWalletKeyAddress } = this.getLegacyAccount(key)
const actualAddress = this._determineAddress(legacyAccount, klaytnWalletKeyAddress, userInputAddress)
return legacyAccount.address.toLowerCase() !== actualAddress.toLowerCase()
}
/**
* getLegacyAccount extracts the private key from the input key and returns an account with the corresponding legacy account key.
* If the input key is KlaytnWalletKey format, it returns klaytnWalletKeyAddress, which is the address extracted from KlaytnWalletKey.
*
* @method getLegacyAccount
* @param {String} key The key parameter can be either normal private key or KlaytnWalletKey format.
* @return {Object}
*/
Accounts.prototype.getLegacyAccount = function getLegacyAccount(key) {
const parsed = utils.parsePrivateKey(key)
if (!utils.isValidPrivateKey(parsed.privateKey)) {
throw new Error('Invalid private key')
}
const privateKey = utils.addHexPrefix(parsed.privateKey)
const account = this._addAccountFunctions(Account.fromObject(AccountLib.fromPrivate(privateKey)))
return { legacyAccount: account, klaytnWalletKeyAddress: parsed.address }
}
/**
* signTransaction signs to transaction with private key.
* If there are signatures(feePayerSignatures if the fee payer signs) in tx entered as a parameter,
* the signatures(feePayerSignatures if the fee payer signs) are appended.
*
* @method signTransaction
* @param {String|Object} tx The transaction to sign.
* @param {String|Array} privateKey The private key to use for signing.
* @param {String} callback The callback function to call.
* @return {Object}
*/
Accounts.prototype.signTransaction = function signTransaction() {
const _this = this
let isLegacy = false
let isFeePayer = false
let existedSenderSignatures = []
let existedFeePayerSignatures = []
let result
let tx
let privateKey
let callback
const handleError = e => {
e = e instanceof Error ? e : new Error(e)
if (callback) callback(e)
return Promise.reject(e)
}
try {
const resolved = resolveArgsForSignTransaction(arguments)
tx = resolved.tx
privateKey = resolved.privateKey
callback = resolved.callback
} catch (e) {
return handleError(e)
}
// If the user signs an RLP encoded transaction, tx is of type string.
if (_.isString(tx)) {
tx = decodeFromRawTransaction(tx)
}
// Validate tx object
const error = helpers.validateFunction.validateParams(tx)
if (error) return handleError(error)
if (tx.senderRawTransaction) {
if (tx.feePayerSignatures) {
existedFeePayerSignatures = existedFeePayerSignatures.concat(tx.feePayerSignatures)
}
try {
// Decode senderRawTransaction to get signatures of fee payer
const { senderRawTransaction, feePayer, feePayerSignatures } = splitFeePayer(tx.senderRawTransaction)
// feePayer !== '0x' means that in senderRawTransaction there are feePayerSignatures
if (feePayer !== '0x') {
// The feePayer inside the tx object does not match the feePayer information contained in the senderRawTransaction.
if (feePayer.toLowerCase() !== tx.feePayer.toLowerCase()) {
return handleError(
`Invalid feePayer: The fee payer(${feePayer}) included in the transaction does not match the fee payer(${tx.feePayer}) you want to sign.`
)
}
existedFeePayerSignatures = existedFeePayerSignatures.concat(feePayerSignatures)
}
tx.senderRawTransaction = senderRawTransaction
isFeePayer = true
} catch (e) {
return handleError(e)
}
} else {
isLegacy = !!(tx.type === undefined || tx.type === 'LEGACY')
if (tx.signatures) {
// if there is existed signatures or feePayerSignatures, those should be preserved.
if (isLegacy) {
return handleError('Legacy transaction cannot be signed with multiple keys.')
}
existedSenderSignatures = existedSenderSignatures.concat(tx.signatures)
}
}
// When privateKey is undefined, find Account from Wallet.
if (privateKey === undefined) {
try {
const account = this.wallet.getAccount(isFeePayer ? tx.feePayer : tx.from)
if (!account) {
return handleError(
'Failed to find get private key to sign. The account you want to use for signing must exist in caver.klay.accounts.wallet or you must pass the private key as a parameter.'
)
}
privateKey = this._getRoleKey(tx, account)
} catch (e) {
return handleError(e)
}
}
const privateKeys = _.isArray(privateKey) ? privateKey : [privateKey]
try {
for (let i = 0; i < privateKeys.length; i++) {
const parsed = utils.parsePrivateKey(privateKeys[i])
privateKeys[i] = parsed.privateKey
privateKeys[i] = utils.addHexPrefix(privateKeys[i])
if (!utils.isValidPrivateKey(privateKeys[i])) {
return handleError('Invalid private key')
}
}
} catch (e) {
return handleError(e)
}
// Attempting to sign with a decoupled account into a legacy type transaction should be rejected.
if (isLegacy) {
if (privateKeys.length > 1) {
return handleError('Legacy transaction cannot signed with multiple keys')
}
if (_this.isDecoupled(privateKeys[0], tx.from)) {
return handleError('A legacy transaction must be with a legacy account key')
}
}
function signed(txObject) {
try {
// Guarantee all property in transaction is hex.
txObject = helpers.formatters.inputCallFormatter(txObject)
const transaction = coverInitialTxValue(txObject)
const rlpEncoded = encodeRLPByTxType(transaction)
const messageHash = Hash.keccak256(rlpEncoded)
const sigs = isFeePayer ? existedFeePayerSignatures : existedSenderSignatures
for (const p of privateKeys) {
const signature = AccountLib.makeSigner(Nat.toNumber(transaction.chainId || '0x1') * 2 + 35)(messageHash, p)
const [v, r, s] = AccountLib.decodeSignature(signature).map(sig => utils.makeEven(utils.trimLeadingZero(sig)))
sigs.push([v, r, s])
}
// makeRawTransaction will return signatures and feePayerSignatures with duplicates removed.
const { rawTransaction, signatures, feePayerSignatures } = makeRawTransaction(rlpEncoded, sigs, transaction)
result = {
messageHash,
v: sigs[0][0],
r: sigs[0][1],
s: sigs[0][2],
rawTransaction,
txHash: Hash.keccak256(rawTransaction),
senderTxHash: getSenderTxHash(rawTransaction),
}
if (isFeePayer) {
result.feePayerSignatures = feePayerSignatures
} else {
result.signatures = signatures
}
} catch (e) {
callback(e)
return Promise.reject(e)
}
callback(null, result)
return result
}
if (tx.nonce !== undefined && tx.chainId !== undefined && tx.gasPrice !== undefined) {
return Promise.resolve(signed(tx))
}
// When the feePayer signs a transaction, required information is only chainId.
if (isFeePayer) {
return Promise.all([isNot(tx.chainId) ? _this._klaytnCall.getChainId() : tx.chainId]).then(function(args) {
if (isNot(args[0])) {
throw new Error(`"chainId" couldn't be fetched: ${JSON.stringify(args)}`)
}
return signed(_.extend(tx, { chainId: args[0] }))
})
}
// Otherwise, get the missing info from the Klaytn Node
return Promise.all([
isNot(tx.chainId) ? _this._klaytnCall.getChainId() : tx.chainId,
isNot(tx.gasPrice) ? _this._klaytnCall.getGasPrice() : tx.gasPrice,
isNot(tx.nonce) ? _this._klaytnCall.getTransactionCount(tx.from, 'pending') : tx.nonce,
]).then(function(args) {
if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) {
throw new Error(`One of the values "chainId", "gasPrice", or "nonce" couldn't be fetched: ${JSON.stringify(args)}`)
}
return signed(
_.extend(tx, {
chainId: args[0],
gasPrice: args[1],
nonce: args[2],
})
)
})
}
/**
* feePayerSignTransaction calls signTransaction, creating a format for feePayer to sign the transaction.
* If there are feePayerSignatures in tx entered as a parameter, the signatures for fee payer are appended.
*
* @method feePayerSignTransaction
* @param {Object|String} tx The transaction to sign.
* @param {String} feePayer The address of fee payer.
* @param {String|Array} privateKey The private key to use for signing.
* @param {Function} callback The callback function to call.
* @return {Object}
*/
Accounts.prototype.feePayerSignTransaction = function feePayerSignTransaction() {
const _this = this
let tx
let feePayer
let privateKey
let callback
const handleError = e => {
e = e instanceof Error ? e : new Error(e)
if (callback) callback(e)
return Promise.reject(e)
}
try {
const resolved = resolveArgsForFeePayerSignTransaction(arguments)
tx = resolved.tx
feePayer = resolved.feePayer
privateKey = resolved.privateKey
callback = resolved.callback
} catch (e) {
return handleError(e)
}
if (_.isString(tx)) {
return this.signTransaction({ senderRawTransaction: tx, feePayer }, privateKey, callback)
}
if (!tx.feePayer || tx.feePayer === '0x') {
tx.feePayer = feePayer
}
if (!tx.senderRawTransaction) {
if (!tx.type || !tx.type.includes('FEE_DELEGATED')) {
return handleError(`Failed to sign transaction with fee payer: invalid transaction type(${tx.type ? tx.type : 'LEGACY'})`)
}
}
const e = helpers.validateFunction.validateParams(tx)
if (e) {
return handleError(e)
}
if (tx.feePayer.toLowerCase() !== feePayer.toLowerCase()) {
return handleError('Invalid parameter: The address of fee payer does not match.')
}
if (tx.senderRawTransaction) {
return this.signTransaction(tx, privateKey, callback)
}
return Promise.all([
isNot(tx.chainId) ? _this._klaytnCall.getChainId() : tx.chainId,
isNot(tx.gasPrice) ? _this._klaytnCall.getGasPrice() : tx.gasPrice,
isNot(tx.nonce) ? _this._klaytnCall.getTransactionCount(tx.from, 'pending') : tx.nonce,
]).then(function(args) {
if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) {
throw new Error(`One of the values "chainId", "gasPrice", or "nonce" couldn't be fetched: ${JSON.stringify(args)}`)
}
let transaction = _.extend(tx, {
chainId: args[0],
gasPrice: args[1],
nonce: args[2],
})
transaction = helpers.formatters.inputCallFormatter(transaction)
transaction = coverInitialTxValue(transaction)
const rlpEncoded = encodeRLPByTxType(transaction)
const sig = transaction.signatures ? transaction.signatures : [['0x01', '0x', '0x']]
const { rawTransaction } = makeRawTransaction(rlpEncoded, sig, transaction)
return _this.signTransaction({ senderRawTransaction: rawTransaction, feePayer }, privateKey, callback)
})
}
/**
* getRawTransactionWithSignatures returns object which contains rawTransaction.
*
* @method getRawTransactionWithSignatures
* @param {Object} tx The transaction object which contains signatures or feePayerSignatures.
* @param {Function} callback The callback function to call.
* @return {Object}
*/
Accounts.prototype.getRawTransactionWithSignatures = function getRawTransactionWithSignatures(tx, callback) {
const _this = this
let result
callback = callback || function() {}
const handleError = e => {
e = e instanceof Error ? e : new Error(e)
if (callback) callback(e)
return Promise.reject(e)
}
if (!tx || !_.isObject(tx)) {
return handleError('Invalid parameter: The transaction must be defined as an object')
}
if (!tx.signatures && !tx.feePayerSignatures) {
return handleError('There are no signatures or feePayerSignatures defined in the transaction object.')
}
const error = helpers.validateFunction.validateParams(tx)
if (error) return handleError(error)
if (tx.senderRawTransaction) {
tx.feePayerSignatures = tx.feePayerSignatures || [['0x01', '0x', '0x']]
const decoded = decodeFromRawTransaction(tx.senderRawTransaction)
// feePayer !== '0x' means that in senderRawTransaction there are feePayerSignatures
if (decoded.feePayer !== '0x' && !utils.isEmptySig(decoded.feePayerSignatures)) {
if (decoded.feePayer.toLowerCase() !== tx.feePayer.toLowerCase()) {
return handleError('Invalid feePayer')
}
tx.feePayerSignatures = tx.feePayerSignatures.concat(decoded.feePayerSignatures)
}
decoded.feePayer = tx.feePayer
decoded.feePayerSignatures = tx.feePayerSignatures
if (tx.signatures) {
decoded.signatures = decoded.signatures.concat(tx.signatures)
}
tx = decoded
}
function signed(txObject) {
try {
// Guarantee all property in transaction is hex.
txObject = helpers.formatters.inputCallFormatter(txObject)
const transaction = coverInitialTxValue(txObject)
const rlpEncoded = encodeRLPByTxType(transaction)
let sigs = transaction.signatures ? transaction.signatures : ['0x01', '0x', '0x']
if (!_.isArray(sigs[0])) sigs = [sigs]
const { rawTransaction, signatures, feePayerSignatures } = makeRawTransaction(rlpEncoded, sigs, transaction)
result = {
rawTransaction,
txHash: Hash.keccak256(rawTransaction),
senderTxHash: getSenderTxHash(rawTransaction),
}
if (signatures && !utils.isEmptySig(signatures)) {
result.signatures = signatures
}
if (feePayerSignatures && !utils.isEmptySig(feePayerSignatures)) {
result.feePayerSignatures = feePayerSignatures
}
} catch (e) {
callback(e)
return Promise.reject(e)
}
callback(null, result)
return result
}
if (tx.nonce !== undefined && tx.chainId !== undefined && tx.gasPrice !== undefined) {
return Promise.resolve(signed(tx))
}
// Otherwise, get the missing info from the Klaytn Node
return Promise.all([
isNot(tx.chainId) ? _this._klaytnCall.getChainId() : tx.chainId,
isNot(tx.gasPrice) ? _this._klaytnCall.getGasPrice() : tx.gasPrice,
isNot(tx.nonce) ? _this._klaytnCall.getTransactionCount(tx.from, 'pending') : tx.nonce,
]).then(function(args) {
if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) {
throw new Error(`One of the values "chainId", "gasPrice", or "nonce" couldn't be fetched: ${JSON.stringify(args)}`)
}
return signed(
_.extend(tx, {
chainId: args[0],
gasPrice: args[1],
nonce: args[2],
})
)
})
}
/**
* combineSignatures combines RLP encoded raw transaction strings.
* combineSignatures compares transaction before combining, and if values in field are not same, this throws error.
* The comparison allows that the address of the fee payer is '0x'(default value) for some transactions while the other transactions have a specific fee payer. This is for the use case that some transactions do not have the fee payer's information.
* In this case, feePayer field doesn't have to be compared with other transaction.
*
* @method combineSignatures
* @param {Array} rawTransactions The array of raw transaction string to combine.
* @param {Function} callback The callback function to call.
* @return {Object}
*/
Accounts.prototype.combineSignatures = function combineSignatures(rawTransactions, callback) {
let decodedTx
let senders = []