-
Notifications
You must be signed in to change notification settings - Fork 28
/
Wallet.js
1405 lines (1218 loc) · 40 KB
/
Wallet.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
/* globals uint8_hex nacl blake2bInit blake2bUpdate blake2bFinal hex_uint8 bigInt
accountFromHexKey dec2hex keyFromAccount TextDecoder TextEncoder Logger */
var pbkdf2 = require('pbkdf2')
var crypto = require('crypto')
var assert = require('assert')
var Block = require('./Block')
var Buffer = require('buffer').Buffer
var MAIN_NET_WORK_THRESHOLD = 'ffffffc000000000'
var BLOCK_BIT_LEN = 128
var Iso10126 = {
/*
* Fills remaining block space with random byte values, except for the
* final byte, which denotes the byte length of the padding
*/
pad: function (dataBytes, nBytesPerBlock) {
var nPaddingBytes = nBytesPerBlock - dataBytes.length % nBytesPerBlock
var paddingBytes = crypto.randomBytes(nPaddingBytes - 1)
var endByte = Buffer.from([ nPaddingBytes ])
return Buffer.concat([ dataBytes, paddingBytes, endByte ])
},
unpad: function (dataBytes) {
var nPaddingBytes = dataBytes[dataBytes.length - 1]
return dataBytes.slice(0, -nPaddingBytes)
}
}
var AES = {
CBC: 'aes-256-cbc',
OFB: 'aes-256-ofb',
ECB: 'aes-256-ecb',
/*
* Encrypt / Decrypt with aes-256
* - dataBytes, key, and salt are expected to be buffers
* - default options are mode=CBC and padding=auto (PKCS7)
*/
encrypt: function (dataBytes, key, salt, options) {
options = options || {}
assert(Buffer.isBuffer(dataBytes), 'expected `dataBytes` to be a Buffer')
assert(Buffer.isBuffer(key), 'expected `key` to be a Buffer')
assert(Buffer.isBuffer(salt) || salt === null, 'expected `salt` to be a Buffer or null')
var cipher = crypto.createCipheriv(options.mode || AES.CBC, key, salt || '')
cipher.setAutoPadding(!options.padding)
if (options.padding) dataBytes = options.padding.pad(dataBytes, BLOCK_BIT_LEN / 8)
var encryptedBytes = Buffer.concat([ cipher.update(dataBytes), cipher.final() ])
return encryptedBytes
},
decrypt: function (dataBytes, key, salt, options) {
options = options || {}
assert(Buffer.isBuffer(dataBytes), 'expected `dataBytes` to be a Buffer')
assert(Buffer.isBuffer(key), 'expected `key` to be a Buffer')
assert(Buffer.isBuffer(salt) || salt === null, 'expected `salt` to be a Buffer or null')
var decipher = crypto.createDecipheriv(options.mode || AES.CBC, key, salt || '')
decipher.setAutoPadding(!options.padding)
var decryptedBytes = Buffer.concat([ decipher.update(dataBytes), decipher.final() ])
if (options.padding) decryptedBytes = options.padding.unpad(decryptedBytes)
return decryptedBytes
}
}
function hexRandom (bytes) {
return uint8_hex(nacl.randomBytes(bytes))
}
module.exports = function (password) {
var api = {} // wallet public methods
var priv = {} // wallet priv methods
// Canoe rep is default (see getDefaultRepresentative()
// but this is normally changed immediately based on sharedConfig.
var defaultRepresentative = null
var id = hexRandom(11) // Unique id of this wallet, to be used as reference when handling
var token = hexRandom(32) // Secret token (used as username in server account)
var tokenPass = hexRandom(32) // Secret tokenPass (used as password in server account)
var enableStateBlocks // True if we should produce state blocks
// The following variables are set via useAccount()
var pk // current account public key
var sk // current account secret key
var pendingBalance // current account pending balance
var balance // current account balance
var lastBlock = '' // current account last block
var lastPendingBlock = ''
var pendingBlocks = [] // current account pending blocks
var chain = [] // current account chain
var representative // current account representative
var meta // current account meta data object
var minimumReceive = bigInt(1) // minimum amount to pocket
var keys = [] // wallet keys, accounts, and all necessary data
var recentTxs = []
var walletPendingBlocks = [] // wallet pending blocks
var readyBlocks = [] // wallet blocks signed and worked, ready to broadcast and add to chain
var errorBlocks = [] // blocks which could not be confirmed
var broadcastCallback = null // Callback function to perform broadcast
var enableBroadcast = true // Flag to enable/disable
var pows = {} // Precalculated work for all accounts, filled up regularly
var current = -1 // key being used
var seed = '' // wallet seed
var lastKeyFromSeed = -1 // seed index
var passPhrase = password // wallet password
var iterations = 5000 // pbkdf2 iterations
var checksum // wallet checksum
var ciphered = true
var logger = new Logger()
function newBlock (state) {
// Explicitly or implicitly by wallet setting
var stateBlock = state || enableStateBlocks
return new Block(stateBlock) // State blocks
}
api.debug = function () {
console.log(readyBlocks)
}
api.debugChain = function () {
api.useAccount(keys[1].account)
for (var i in chain) {
console.log(chain[i].getHash(true))
console.log(chain[i].getPrevious())
}
}
api.hasDefaultRepresentative = function () {
return defaultRepresentative !== null
}
api.setDefaultRepresentative = function (rep) {
defaultRepresentative = rep
}
api.getDefaultRepresentative = function () {
return defaultRepresentative || 'nano_3rropjiqfxpmrrkooej4qtmm1pueu36f9ghinpho4esfdor8785a455d16nf'
}
api.setLogger = function (loggerObj) {
logger = loggerObj
}
api.enableStateBlocks = function (bool) {
enableStateBlocks = bool
}
api.getEnableStateBlocks = function () {
return enableStateBlocks
}
api.enableBroadcast = function (bool) {
enableBroadcast = bool
}
api.setBroadcastCallback = function (cb) {
broadcastCallback = cb
}
/**
* Sets the secret key to do all the signing stuff
*
* @param {Array} hex - The secret key byte array
* @throws An exception on invalid secret key length
*/
priv.setSecretKey = function (bytes) {
if (bytes.length !== 32) { throw new Error('Invalid Secret Key length. Should be 32 bytes') }
sk = bytes
pk = nacl.sign.keyPair.fromSecretKey(sk).publicKey
}
/**
* Signs a message with the secret key
*
* @param {Array} message - The message to be signed in a byte array
* @returns {Array} The 64 byte signature
*/
api.sign = function (message) {
return nacl.sign.detached(message, sk)
}
/**
* Signs an alias request with the secret key
*
* @param {Array} fields - The fields to be signed in an array of strings for public signatures its [alias,address] for priv signatures its [alias,address,seed]
* @returns {String} The Hex Signature
*/
api.aliasSignature = function (fields) {
if (current !== -1) {
var context = blake2bInit(32)
for (var i = 0; i < fields.length; i++) {
blake2bUpdate(context, hex_uint8(fields[i]))
}
var data = {
hash: uint8_hex(blake2bFinal(context))
}
data.signature = uint8_hex(nacl.sign.detached(hex_uint8(data.hash), keys[current].priv))
return data
} else {
logger.log('No current account')
return null
}
}
api.checkPass = function (pswd) {
return passPhrase === pswd
}
api.changePass = function (pswd, newPass) {
if (ciphered) { throw new Error('Wallet needs to be decrypted first') }
if (pswd === passPhrase) {
passPhrase = newPass
logger.log('Password changed')
} else { throw new Error('Incorrect password') }
}
api.setIterations = function (newIterationNumber) {
newIterationNumber = parseInt(newIterationNumber)
if (newIterationNumber < 2) {
throw new Error('Minimum iteration number is 2')
}
iterations = newIterationNumber
}
api.setMinimumReceive = function (rawAmount) {
var amount = bigInt(rawAmount)
if (amount.lesser(0)) { return false }
minimumReceive = amount
return true
}
api.getMinimumReceive = function () {
return minimumReceive
}
/**
* Sets a seed for the wallet
*
* @param {string} hexSeed - The 32 byte seed hex encoded
* @throws An exception on malformed seed
*/
api.setSeed = function (hexSeed) {
if (!/[0-9A-F]{64}/i.test(hexSeed)) { throw new Error('Invalid Hex Seed') }
seed = hex_uint8(hexSeed)
}
api.getSeed = function (pswd) {
if (pswd === passPhrase) { return uint8_hex(seed) }
throw new Error('Incorrect password')
}
/**
* Sets a random seed for the wallet
*
* @param {boolean} overwrite - Set to true to overwrite an existing seed
* @throws An exception on existing seed
*/
api.setRandomSeed = function (overwrite = false) {
if (seed && !overwrite) {
throw new Error('Seed already exists. To overwrite use setSeed or set overwrite to true')
}
seed = nacl.randomBytes(32)
}
/**
* Derives a new secret key from the seed and adds it to the wallet
*
* @throws An exception if theres no seed
*/
api.newKeyFromSeed = function () {
if (seed.length !== 32) { throw new Error('Seed should be set first.') }
var index = lastKeyFromSeed + 1
index = hex_uint8(dec2hex(index, 4))
var context = blake2bInit(32)
blake2bUpdate(context, seed)
blake2bUpdate(context, index)
var newKey = blake2bFinal(context)
lastKeyFromSeed++
logger.log('New key generated')
api.addSecretKey(uint8_hex(newKey))
return accountFromHexKey(uint8_hex(nacl.sign.keyPair.fromSecretKey(newKey).publicKey))
}
/**
* Adds a key to the wallet
*
* @param {string} hex - The secret key hex encoded
* @throws An exception on invalid secret key length
* @throws An exception on invalid hex format
*/
api.addSecretKey = function (hex) {
if (hex.length !== 64) { throw new Error('Invalid Secret Key length. Should be 32 bytes') }
if (!/[0-9A-F]{64}/i.test(hex)) { throw new Error('Invalid Hex Secret Key') }
keys.push(
{
priv: hex_uint8(hex),
pub: nacl.sign.keyPair.fromSecretKey(hex_uint8(hex)).publicKey,
account: accountFromHexKey(uint8_hex(nacl.sign.keyPair.fromSecretKey(hex_uint8(hex)).publicKey)),
balance: bigInt(0),
pendingBalance: bigInt(0),
lastBlock: '',
lastPendingBlock: '',
subscribed: false,
chain: [],
representative: api.getDefaultRepresentative(),
meta: { label: '' }
}
)
logger.log('New key added to wallet.')
}
/**
*
* @param {boolean} hex - To return the result hex encoded
* @returns {string} The public key hex encoded
* @returns {Array} The public key in a byte array
*/
api.getPublicKey = function (hex = false) {
if (hex) { return uint8_hex(pk) }
return pk
}
/**
*
* @returns {string} The current account
*/
api.getCurrentAccount = function () {
if (current !== -1) { return keys[current].account }
return null
}
/**
* List all the accounts in the wallet
*
* @returns {Array}
*/
api.getAccounts = function () {
var accounts = []
for (var i in keys) {
accounts.push({
id: keys[i].account,
balance: bigInt(keys[i].balance),
pendingBalance: bigInt(keys[i].pendingBalance),
name: keys[i].meta.label,
meta: keys[i].meta
})
}
return accounts
}
/**
* List all the account ids in the wallet
*
* @returns {Array}
*/
api.getAccountIds = function () {
var ids = []
for (var i in keys) {
ids.push(keys[i].account)
}
return ids
}
/**
* Get a single account in the wallet given account number
*
* @returns {Array}
*/
api.getAccount = function (account) {
var key = api.findKey(account)
if (!key) return null
return {
id: key.account,
balance: bigInt(key.balance),
pendingBalance: bigInt(key.pendingBalance),
name: key.meta.label,
meta: key.meta
}
}
/**
* Find key for given account number
*/
api.findKey = function (account) {
for (var i in keys) {
if (keys[i].account === account) {
return keys[i]
}
}
return null
}
/**
* Switches the account being used by the wallet
*
* @param {string} accountToUse
* @throws An exception if the account is not found in the wallet
*/
api.useAccount = function (accountToUse) {
// save current account status
if (current !== -1) {
keys[current].balance = balance
keys[current].pendingBalance = pendingBalance
keys[current].lastBlock = lastBlock
keys[current].lastPendingBlock = lastPendingBlock
keys[current].chain = chain
keys[current].pendingBlocks = pendingBlocks
keys[current].representative = representative
keys[current].meta = meta
}
for (var i in keys) {
if (keys[i].account === accountToUse) {
priv.setSecretKey(keys[i].priv)
balance = keys[i].balance
pendingBalance = keys[i].pendingBalance
current = i
lastBlock = keys[i].lastBlock
lastPendingBlock = keys[i].lastPendingBlock
chain = keys[i].chain
representative = keys[i].representative
meta = keys[i].meta
return
}
}
throw new Error('Account not found in wallet (' + accountToUse + ') ' + JSON.stringify(api.getAccounts()))
}
api.importChain = function (blocks, acc) {
api.useAccount(acc)
var last = chain.length > 0 ? chain[chain.length - 1].getHash(true) : uint8_hex(pk)
// verify chain
for (var i in blocks) {
if (blocks[i].getPrevious() !== last) { throw new Error('Invalid chain') }
if (!api.verifyBlock(blocks[i])) { throw new Error('There is an invalid block') }
}
}
api.resetChain = function (acc) {
api.useAccount(acc)
balance = bigInt(0)
pendingBalance = bigInt(0)
pendingBlocks = []
lastBlock = ''
lastPendingBlock = ''
chain = []
priv.save()
}
api.getLastNBlocks = function (acc, n, offset = 0) {
var temp = keys[current].account
api.useAccount(acc)
var blocks = []
if (n > chain.length) { n = chain.length }
for (var i = chain.length - 1 - offset; i > chain.length - 1 - n - offset; i--) {
blocks.push(chain[i])
}
api.useAccount(temp)
return blocks
}
api.getBlocksUpTo = function (acc, hash) {
var temp = keys[current].account
api.useAccount(acc)
var blocks = []
for (var i = chain.length - 1; i > 0; i--) {
blocks.push(chain[i])
if (chain[i].getHash(true) === hash) { break }
}
api.useAccount(temp)
return blocks
}
api.getAccountBlockCount = function (acc) {
var temp = keys[current].account
api.useAccount(acc)
var n = chain.length
api.useAccount(temp)
return n
}
/**
* Generates a block signature from the block hash using the secret key
*
* @param {string} blockHash - The block hash hex encoded
* @throws An exception on invalid block hash length
* @throws An exception on invalid block hash hex encoding
* @returns {string} The 64 byte hex encoded signature
*/
api.signBlock = function (block) {
var blockHash = block.getHash()
if (blockHash.length !== 32) {
throw new Error('Invalid block hash length. It should be 32 bytes')
}
block.setSignature(uint8_hex(api.sign(blockHash)))
block.setAccount(keys[current].account)
logger.log('Block ' + block.getHash(true) + ' signed.')
}
/**
* Verifies a block signature given its hash, sig and NANO account
*
* @param {string} blockHash - 32 byte hex encoded block hash
* @param {string} blockSignature - 64 byte hex encoded signature
* @param {string} account - A NANO account supposed to have signed the block
* @returns {boolean}
*/
api.verifyBlockSignature = function (blockHash, blockSignature, account) {
var pubKey = hex_uint8(keyFromAccount(account))
return nacl.sign.detached.verify(hex_uint8(blockHash), hex_uint8(blockSignature), pubKey)
}
api.verifyBlock = function (block) {
return api.verifyBlockSignature(block.getHash(true), block.getSignature(), block.getAccount())
}
/**
* Returns current account balance
*
* @returns {number} balance
*/
api.getBalance = function () {
return balance || keys[current].balance
}
/**
* Returns current account pending balance (not pocketed)
*
* @returns {number} pendingBalance
*/
api.getPendingBalance = function () {
// return pendingBalance ? pendingBalance : keys[current].pendingBalance;
var am = bigInt(0)
for (var i in pendingBlocks) {
if (pendingBlocks[i].getType() === 'open' || pendingBlocks[i].getType() === 'receive') {
am = am.add(pendingBlocks[i].getAmount())
}
}
return am
}
api.getRepresentative = function (acc = false) {
if (!acc) { return representative }
api.useAccount(acc)
return representative
}
priv.setRepresentative = function (repr) {
representative = repr
keys[current].representative = repr
}
/**
* Updates current account balance
*
* @param {number} newBalance - The new balance in rai units
*/
priv.setBalance = function (newBalance) {
balance = bigInt(newBalance)
keys[current].balance = balance
}
priv.setPendingBalance = function (newBalance) {
pendingBalance = bigInt(newBalance)
keys[current].pendingBalance = pendingBalance
}
api.getAccountBalance = function (acc) {
api.useAccount(acc)
return api.getBalanceUpToBlock(0)
}
api.getWalletPendingBalance = function () {
var pending = bigInt(0)
for (var i in walletPendingBlocks) {
if (walletPendingBlocks[i].getType() === 'open' || walletPendingBlocks[i].getType() === 'receive') {
pending = pending.add(walletPendingBlocks[i].getAmount())
}
}
return pending
}
api.getWalletBalance = function () {
var bal = bigInt(0)
var temp
for (var i in keys) {
temp = keys[i].balance
bal = bal.add(temp)
}
return bal
}
api.getPoW = function (acc) {
if (acc) {
return pows[acc]
} else {
return pows
}
}
api.recalculateWalletBalances = function () {
for (var i in keys) {
api.useAccount(keys[i].account)
priv.setBalance(api.getBalanceUpToBlock(0))
}
}
api.getBalanceUpToBlock = function (blockHash) {
var sum = bigInt(0)
if (chain.length + pendingBlocks.length === 0) { return sum }
var found = blockHash === 0
var blk
// check pending blocks first
for (var i = pendingBlocks.length - 1; i >= 0; i--) {
blk = pendingBlocks[i]
if (blk.getHash(true) === blockHash) { found = true }
if (found) {
if (blk.isState()) {
return blk.getBalance()
}
if (blk.getType() === 'open' || blk.getType() === 'receive') {
sum = sum.add(blk.getAmount())
} else if (blk.getType() === 'send') {
sum = sum.add(blk.getBalance())
break
}
}
}
for (i = chain.length - 1; i >= 0; i--) {
blk = chain[i]
if (blk.getHash(true) === blockHash) { found = true }
if (found) {
if (blk.isState()) {
return blk.getBalance()
}
if (blk.getType() === 'open' || blk.getType() === 'receive') {
sum = sum.add(blk.getAmount())
} else if (blk.getType() === 'send') {
sum = sum.add(blk.getBalance())
break
}
}
}
return sum
}
/**
* Updates an account balance
*
* @param {number} - The new balance in raw units
* @param {string} Account - The account whose balance is being updated
*/
priv.setAccountBalance = function (newBalance, acc) {
var temp = current
api.useAccount(acc)
priv.setBalance(newBalance)
api.useAccount(keys[temp].account)
}
priv.sumAccountPending = function (acc, amount) {
var temp = current
api.useAccount(acc)
priv.setPendingBalance(api.getPendingBalance().sum(amount))
api.useAccount(keys[temp].account)
}
api.setMeta = function (acc, meta) {
for (var i in keys) {
if (keys[i].account === acc) {
keys[i].meta = meta
return true
}
}
return false
}
api.getMeta = function (acc) {
for (var i in keys) {
if (keys[i].account === acc) {
return keys[i].meta
}
}
return null
}
api.removePendingBlocks = function (account) {
var temp = keys[current].account
api.useAccount(account)
pendingBlocks = []
api.useAccount(temp)
}
api.removePendingBlock = function (blockHash) {
var found = false
for (var i in pendingBlocks) {
var tmp = pendingBlocks[i]
if (tmp.getHash(true) === blockHash) {
pendingBlocks.splice(i, 1)
found = true
}
}
if (!found) {
console.log('Not found')
return
}
for (i in walletPendingBlocks) {
tmp = walletPendingBlocks[i]
if (tmp.getHash(true) === blockHash) {
walletPendingBlocks.splice(i, 1)
return
}
}
}
api.clearWalletPendingBlocks = function () {
walletPendingBlocks = []
}
api.getBlockFromHashAndAccount = function (blockHash, acc) {
api.useAccount(acc)
for (var j = chain.length - 1; j >= 0; j--) {
var blk = chain[j]
if (blk.getHash(true) === blockHash) { return blk }
}
return null
}
api.lastBlockIsState = function () {
if (lastBlock) {
return api.getBlockFromHash(lastBlock).isState()
} else {
return true
// new account
//throw new Error('There is no previous block synced!')
}
}
api.getBlockFromHash = function (blockHash) {
for (var i = 0; i < keys.length; i++) {
api.useAccount(keys[i].account)
for (var j = chain.length - 1; j >= 0; j--) {
var blk = chain[j]
if (blk.getHash(true) === blockHash) { return blk }
}
}
return null
}
api.addBlockToReadyBlocks = function (blk) {
readyBlocks.push(blk)
logger.log('Block ready to be broadcasted: ' + blk.getHash(true))
if (enableBroadcast) {
broadcastCallback(readyBlocks)
}
}
// Check if we already have a precalculated PoW and if so consume it, otherwise
// we will have to wait for work coming in from outside via addWorkToPendingBlock
priv.checkPrecalculated = function (blockHash, acc) {
var precalc = pows[acc]
if (precalc) {
delete pows[acc]
logger.log('Using precalculated work for block: ' + blockHash + ' previous: ' + precalc.hash)
api.addWorkToPendingBlock(precalc.hash, precalc.work)
}
}
api.addPendingSendBlock = function (from, to, amount = 0, message) {
api.useAccount(from)
amount = bigInt(amount)
var bal = api.getBalanceUpToBlock(0)
var remaining = bal.minus(amount)
var blk = newBlock(api.lastBlockIsState())
blk.setSendParameters(lastPendingBlock, to, remaining)
if (blk.isState()) {
blk.setStateParameters(from, representative)
}
blk.build()
api.signBlock(blk)
blk.setAmount(amount)
blk.setAccount(from)
blk.setMessage(message)
lastPendingBlock = blk.getHash(true)
keys[current].lastPendingBlock = lastPendingBlock
priv.setBalance(remaining)
pendingBlocks.push(blk)
walletPendingBlocks.push(blk)
priv.save()
logger.log('New send block ready for work: ' + lastPendingBlock)
priv.checkPrecalculated(lastPendingBlock, from)
return blk
}
api.addPendingReceiveBlock = function (sourceBlockHash, acc, from, amount = 0) {
amount = bigInt(amount)
api.useAccount(acc)
if (amount.lesser(minimumReceive)) {
logger.log('Receive block rejected due to minimum receive amount (' + sourceBlockHash + ')')
return false
}
// make sure this source has not been redeemed yet
for (var i in walletPendingBlocks) {
if (walletPendingBlocks[i].getSource() === sourceBlockHash) { return false }
}
for (i in readyBlocks) {
if (readyBlocks[i].getSource() === sourceBlockHash) { return false }
}
for (i in chain) {
if (chain[i].getSource() === sourceBlockHash) { return false }
}
var blk = newBlock(api.lastBlockIsState())
if (lastPendingBlock.length === 64) {
blk.setReceiveParameters(lastPendingBlock, sourceBlockHash)
} else {
blk.setOpenParameters(sourceBlockHash, acc, api.getDefaultRepresentative())
}
if (blk.isState()) {
var bal = api.getBalanceUpToBlock(0)
var remaining = bal.plus(amount)
blk.setStateParameters(acc, representative, remaining)
}
blk.build()
api.signBlock(blk)
blk.setAmount(amount)
blk.setAccount(acc)
blk.setOrigin(from)
lastPendingBlock = blk.getHash(true)
keys[current].lastPendingBlock = lastPendingBlock
pendingBlocks.push(blk)
walletPendingBlocks.push(blk)
priv.setPendingBalance(api.getPendingBalance().add(amount))
priv.save()
logger.log('New receive block ready for work: ' + lastPendingBlock)
priv.checkPrecalculated(lastPendingBlock, acc)
return blk
}
api.addPendingChangeBlock = function (acc, repr) {
api.useAccount(acc)
if (!lastPendingBlock) { throw new Error('There needs to be at least 1 block in the chain') }
var blk = newBlock(api.lastBlockIsState())
blk.setChangeParameters(lastPendingBlock, repr)
if (blk.isState()) {
var bal = api.getBalanceUpToBlock(0)
blk.setStateParameters(acc, repr, bal)
}
blk.build()
api.signBlock(blk)
blk.setAccount(acc)
lastPendingBlock = blk.getHash(true)
keys[current].lastPendingBlock = lastPendingBlock
pendingBlocks.push(blk)
walletPendingBlocks.push(blk)
priv.save()
logger.log('New change block ready for work: ' + lastPendingBlock)
priv.checkPrecalculated(lastPendingBlock, acc)
return blk
}
api.getPendingBlocks = function () {
return pendingBlocks
}
api.getPendingBlockByHash = function (blockHash) {
for (var i in walletPendingBlocks) {
if (walletPendingBlocks[i].getHash(true) === blockHash) {
return walletPendingBlocks[i]
}
}
return false
}
api.getNextWorkBlockHash = function (acc) {
var result
var temp = keys[current].account
api.useAccount(acc)
if (lastBlock.length > 0) {
result = lastBlock
} else {
result = uint8_hex(pk)
}
api.useAccount(temp)
return result
}
priv.chainPush = function (blk, hash) {
chain.push(blk)
lastBlock = hash
keys[current].lastBlock = hash
}
api.clearPrecalc = function () {
pows = {}
}
api.checkWork = function (work, blockHash) {
var t = hex_uint8(MAIN_NET_WORK_THRESHOLD)
var context = blake2bInit(8, null)
blake2bUpdate(context, hex_uint8(work).reverse())
blake2bUpdate(context, hex_uint8(blockHash))
var threshold = blake2bFinal(context).reverse()
if (threshold[0] === t[0]) {
if (threshold[1] === t[1]) {
if (threshold[2] === t[2]) {
if (threshold[3] >= t[3]) {
return true
}
}
}
}
return false
}
api.getNextPrecalcToWork = function () {
for (var i in keys) {
var acc = keys[i].account
if (!pows[acc]) {
// No precalculated for this account, let's make one
var hash = api.getNextWorkBlockHash(acc)
return {account: acc, hash: hash}
}
}
return null
}
api.addWorkToPrecalc = function (acc, hash, work) {
pows[acc] = {hash: hash, work: work}
}
api.getNextPendingBlockToWork = function () {
if (walletPendingBlocks.length === 0) {
return null
}
return walletPendingBlocks[0].getPrevious()
}
// Called when work has been found for hash
api.addWorkToPendingBlock = function (hash, work) {
if (!api.checkWork(work, hash)) {
logger.warn('Invalid PoW received (' + work + ') (' + hash + ').')
return false
}
// Find pending block with this hash as previous
for (var j in walletPendingBlocks) {
if (walletPendingBlocks[j].getPrevious() === hash) {
// Yes, this is the one, add work to it
var pendingBlk = walletPendingBlocks[j]