forked from breadwallet/breadwallet-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BRWallet.c
1215 lines (1000 loc) · 46.6 KB
/
BRWallet.c
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
//
// BRWallet.c
//
// Created by Aaron Voisine on 9/1/15.
// Copyright (c) 2015 breadwallet LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "BRWallet.h"
#include "BRSet.h"
#include "BRAddress.h"
#include "BRArray.h"
#include <stdlib.h>
#include <inttypes.h>
#include <limits.h>
#include <float.h>
#include <pthread.h>
#include <assert.h>
struct BRWalletStruct {
uint64_t balance, totalSent, totalReceived, feePerKb, *balanceHist;
uint32_t blockHeight;
BRUTXO *utxos;
BRTransaction **transactions;
BRMasterPubKey masterPubKey;
BRAddress *internalChain, *externalChain;
BRSet *allTx, *invalidTx, *pendingTx, *spentOutputs, *usedAddrs, *allAddrs;
void *callbackInfo;
void (*balanceChanged)(void *info, uint64_t balance);
void (*txAdded)(void *info, BRTransaction *tx);
void (*txUpdated)(void *info, const UInt256 txHashes[], size_t txCount, uint32_t blockHeight, uint32_t timestamp);
void (*txDeleted)(void *info, UInt256 txHash, int notifyUser, int recommendRescan);
pthread_mutex_t lock;
};
inline static uint64_t _txFee(uint64_t feePerKb, size_t size)
{
uint64_t standardFee = ((size + 999)/1000)*TX_FEE_PER_KB, // standard fee based on tx size rounded up to nearest kb
fee = (((size*feePerKb/1000) + 99)/100)*100; // fee using feePerKb, rounded up to nearest 100 satoshi
return (fee > standardFee) ? fee : standardFee;
}
// chain position of first tx output address that appears in chain
inline static size_t _txChainIndex(const BRTransaction *tx, const BRAddress *addrChain)
{
for (size_t i = array_count(addrChain); i > 0; i--) {
for (size_t j = 0; j < tx->outCount; j++) {
if (BRAddressEq(tx->outputs[j].address, &addrChain[i - 1])) return i - 1;
}
}
return SIZE_MAX;
}
inline static int _BRWalletTxIsAscending(BRWallet *wallet, const BRTransaction *tx1, const BRTransaction *tx2)
{
if (! tx1 || ! tx2) return 0;
if (tx1->blockHeight > tx2->blockHeight) return 1;
if (tx1->blockHeight < tx2->blockHeight) return 0;
for (size_t i = 0; i < tx1->inCount; i++) {
if (UInt256Eq(tx1->inputs[i].txHash, tx2->txHash)) return 1;
}
for (size_t i = 0; i < tx2->inCount; i++) {
if (UInt256Eq(tx2->inputs[i].txHash, tx1->txHash)) return 0;
}
for (size_t i = 0; i < tx1->inCount; i++) {
if (_BRWalletTxIsAscending(wallet, BRSetGet(wallet->allTx, &(tx1->inputs[i].txHash)), tx2)) return 1;
}
return 0;
}
inline static int _BRWalletTxCompare(BRWallet *wallet, const BRTransaction *tx1, const BRTransaction *tx2)
{
size_t i, j;
if (_BRWalletTxIsAscending(wallet, tx1, tx2)) return 1;
if (_BRWalletTxIsAscending(wallet, tx2, tx1)) return -1;
i = _txChainIndex(tx1, wallet->internalChain);
j = _txChainIndex(tx2, (i == SIZE_MAX) ? wallet->externalChain : wallet->internalChain);
if (i == SIZE_MAX && j != SIZE_MAX) i = _txChainIndex((BRTransaction *)tx1, wallet->externalChain);
if (i != SIZE_MAX && j != SIZE_MAX && i != j) return (i > j) ? 1 : -1;
return 0;
}
// inserts tx into wallet->transactions, keeping wallet->transactions sorted by date, oldest first (insertion sort)
inline static void _BRWalletInsertTx(BRWallet *wallet, BRTransaction *tx)
{
size_t i = array_count(wallet->transactions);
array_set_count(wallet->transactions, i + 1);
while (i > 0 && _BRWalletTxCompare(wallet, wallet->transactions[i - 1], tx) > 0) {
wallet->transactions[i] = wallet->transactions[i - 1];
i--;
}
wallet->transactions[i] = tx;
}
// non-threadsafe version of BRWalletContainsTransaction()
static int _BRWalletContainsTx(BRWallet *wallet, const BRTransaction *tx)
{
int r = 0;
for (size_t i = 0; ! r && i < tx->outCount; i++) {
if (BRSetContains(wallet->allAddrs, tx->outputs[i].address)) r = 1;
}
for (size_t i = 0; ! r && i < tx->inCount; i++) {
BRTransaction *t = BRSetGet(wallet->allTx, &tx->inputs[i].txHash);
uint32_t n = tx->inputs[i].index;
if (t && n < t->outCount && BRSetContains(wallet->allAddrs, t->outputs[n].address)) r = 1;
}
return r;
}
//static int _BRWalletTxIsSend(BRWallet *wallet, BRTransaction *tx)
//{
// int r = 0;
//
// for (size_t i = 0; ! r && i < tx->inCount; i++) {
// if (BRSetContains(wallet->allAddrs, tx->inputs[i].address)) r = 1;
// }
//
// return r;
//}
static void _BRWalletUpdateBalance(BRWallet *wallet)
{
int isInvalid, isPending;
uint64_t balance = 0, prevBalance = 0;
time_t now = time(NULL);
size_t i, j;
BRTransaction *tx, *t;
array_clear(wallet->utxos);
array_clear(wallet->balanceHist);
BRSetClear(wallet->spentOutputs);
BRSetClear(wallet->invalidTx);
BRSetClear(wallet->pendingTx);
BRSetClear(wallet->usedAddrs);
wallet->totalSent = 0;
wallet->totalReceived = 0;
for (i = 0; i < array_count(wallet->transactions); i++) {
tx = wallet->transactions[i];
// check if any inputs are invalid or already spent
if (tx->blockHeight == TX_UNCONFIRMED) {
for (j = 0, isInvalid = 0; ! isInvalid && j < tx->inCount; j++) {
if (BRSetContains(wallet->spentOutputs, &tx->inputs[j]) ||
BRSetContains(wallet->invalidTx, &tx->inputs[j].txHash)) isInvalid = 1;
}
if (isInvalid) {
BRSetAdd(wallet->invalidTx, tx);
array_add(wallet->balanceHist, balance);
continue;
}
}
// add inputs to spent output set
for (j = 0; j < tx->inCount; j++) {
BRSetAdd(wallet->spentOutputs, &tx->inputs[j]);
}
// check if tx is pending
if (tx->blockHeight == TX_UNCONFIRMED) {
isPending = (BRTransactionSize(tx) > TX_MAX_SIZE) ? 1 : 0; // check tx size is under TX_MAX_SIZE
for (j = 0; ! isPending && j < tx->outCount; j++) {
if (tx->outputs[j].amount < TX_MIN_OUTPUT_AMOUNT) isPending = 1; // check that no outputs are dust
}
for (j = 0; ! isPending && j < tx->inCount; j++) {
if (tx->inputs[j].sequence < UINT32_MAX - 1) isPending = 1; // check for replace-by-fee
if (tx->inputs[j].sequence < UINT32_MAX && tx->lockTime < TX_MAX_LOCK_HEIGHT &&
tx->lockTime > wallet->blockHeight + 1) isPending = 1; // future lockTime
if (tx->inputs[j].sequence < UINT32_MAX && tx->lockTime > now) isPending = 1; // future lockTime
if (BRSetContains(wallet->pendingTx, &tx->inputs[j].txHash)) isPending = 1; // check for pending inputs
}
if (isPending) {
BRSetAdd(wallet->pendingTx, tx);
array_add(wallet->balanceHist, balance);
continue;
}
}
// add outputs to UTXO set
// TODO: don't add outputs below TX_MIN_OUTPUT_AMOUNT
// TODO: don't add coin generation outputs < 100 blocks deep
// NOTE: balance/UTXOs will then need to be recalculated when last block changes
for (j = 0; j < tx->outCount; j++) {
if (tx->outputs[j].address[0] != '\0') {
BRSetAdd(wallet->usedAddrs, tx->outputs[j].address);
if (BRSetContains(wallet->allAddrs, tx->outputs[j].address)) {
array_add(wallet->utxos, ((BRUTXO) { tx->txHash, (uint32_t)j }));
balance += tx->outputs[j].amount;
}
}
}
// transaction ordering is not guaranteed, so check the entire UTXO set against the entire spent output set
for (j = array_count(wallet->utxos); j > 0; j--) {
if (! BRSetContains(wallet->spentOutputs, &wallet->utxos[j - 1])) continue;
t = BRSetGet(wallet->allTx, &wallet->utxos[j - 1].hash);
balance -= t->outputs[wallet->utxos[j - 1].n].amount;
array_rm(wallet->utxos, j - 1);
}
if (prevBalance < balance) wallet->totalReceived += balance - prevBalance;
if (balance < prevBalance) wallet->totalSent += prevBalance - balance;
array_add(wallet->balanceHist, balance);
prevBalance = balance;
}
assert(array_count(wallet->balanceHist) == array_count(wallet->transactions));
wallet->balance = balance;
}
// allocates and populates a BRWallet struct which must be freed by calling BRWalletFree()
BRWallet *BRWalletNew(BRTransaction *transactions[], size_t txCount, BRMasterPubKey mpk)
{
BRWallet *wallet = NULL;
BRTransaction *tx;
assert(transactions != NULL || txCount == 0);
wallet = calloc(1, sizeof(*wallet));
assert(wallet != NULL);
array_new(wallet->utxos, 100);
array_new(wallet->transactions, txCount + 100);
wallet->feePerKb = DEFAULT_FEE_PER_KB;
wallet->masterPubKey = mpk;
array_new(wallet->internalChain, 100);
array_new(wallet->externalChain, 100);
array_new(wallet->balanceHist, txCount + 100);
wallet->allTx = BRSetNew(BRTransactionHash, BRTransactionEq, txCount + 100);
wallet->invalidTx = BRSetNew(BRTransactionHash, BRTransactionEq, 10);
wallet->pendingTx = BRSetNew(BRTransactionHash, BRTransactionEq, 10);
wallet->spentOutputs = BRSetNew(BRUTXOHash, BRUTXOEq, txCount + 100);
wallet->usedAddrs = BRSetNew(BRAddressHash, BRAddressEq, txCount + 100);
wallet->allAddrs = BRSetNew(BRAddressHash, BRAddressEq, txCount + 100);
pthread_mutex_init(&wallet->lock, NULL);
for (size_t i = 0; transactions && i < txCount; i++) {
tx = transactions[i];
if (! BRTransactionIsSigned(tx) || BRSetContains(wallet->allTx, tx)) continue;
BRSetAdd(wallet->allTx, tx);
_BRWalletInsertTx(wallet, tx);
for (size_t j = 0; j < tx->outCount; j++) {
if (tx->outputs[j].address[0] != '\0') BRSetAdd(wallet->usedAddrs, tx->outputs[j].address);
}
}
BRWalletUnusedAddrs(wallet, NULL, SEQUENCE_GAP_LIMIT_EXTERNAL, 0);
BRWalletUnusedAddrs(wallet, NULL, SEQUENCE_GAP_LIMIT_INTERNAL, 1);
_BRWalletUpdateBalance(wallet);
if (txCount > 0 && ! _BRWalletContainsTx(wallet, transactions[0])) { // verify transactions match master pubKey
BRWalletFree(wallet);
wallet = NULL;
}
return wallet;
}
// not thread-safe, set callbacks once after BRWalletNew(), before calling other BRWallet functions
// info is a void pointer that will be passed along with each callback call
// void balanceChanged(void *, uint64_t) - called when the wallet balance changes
// void txAdded(void *, BRTransaction *) - called when transaction is added to the wallet
// void txUpdated(void *, const UInt256[], size_t, uint32_t, uint32_t)
// - called when the blockHeight or timestamp of previously added transactions are updated
// void txDeleted(void *, UInt256) - called when a previously added transaction is removed from the wallet
// NOTE: if a transaction is deleted, and BRWalletAmountSentByTx() is greater than 0, recommend the user do a rescan
void BRWalletSetCallbacks(BRWallet *wallet, void *info,
void (*balanceChanged)(void *info, uint64_t balance),
void (*txAdded)(void *info, BRTransaction *tx),
void (*txUpdated)(void *info, const UInt256 txHashes[], size_t txCount, uint32_t blockHeight,
uint32_t timestamp),
void (*txDeleted)(void *info, UInt256 txHash, int notifyUser, int recommendRescan))
{
assert(wallet != NULL);
wallet->callbackInfo = info;
wallet->balanceChanged = balanceChanged;
wallet->txAdded = txAdded;
wallet->txUpdated = txUpdated;
wallet->txDeleted = txDeleted;
}
// wallets are composed of chains of addresses
// each chain is traversed until a gap of a number of addresses is found that haven't been used in any transactions
// this function writes to addrs an array of <gapLimit> unused addresses following the last used address in the chain
// the internal chain is used for change addresses and the external chain for receive addresses
// addrs may be NULL to only generate addresses for BRWalletContainsAddress()
// returns the number addresses written to addrs
size_t BRWalletUnusedAddrs(BRWallet *wallet, BRAddress addrs[], uint32_t gapLimit, int internal)
{
BRAddress *addrChain;
size_t i, j = 0, count, startCount;
uint32_t chain = (internal) ? SEQUENCE_INTERNAL_CHAIN : SEQUENCE_EXTERNAL_CHAIN;
assert(wallet != NULL);
assert(gapLimit > 0);
pthread_mutex_lock(&wallet->lock);
addrChain = (internal) ? wallet->internalChain : wallet->externalChain;
i = count = startCount = array_count(addrChain);
// keep only the trailing contiguous block of addresses with no transactions
while (i > 0 && ! BRSetContains(wallet->usedAddrs, &addrChain[i - 1])) i--;
while (i + gapLimit > count) { // generate new addresses up to gapLimit
BRKey key;
BRAddress address = BR_ADDRESS_NONE;
uint8_t pubKey[BRBIP32PubKey(NULL, 0, wallet->masterPubKey, chain, count)];
size_t len = BRBIP32PubKey(pubKey, sizeof(pubKey), wallet->masterPubKey, chain, (uint32_t)count);
if (! BRKeySetPubKey(&key, pubKey, len)) break;
if (! BRKeyAddress(&key, address.s, sizeof(address)) || BRAddressEq(&address, &BR_ADDRESS_NONE)) break;
array_add(addrChain, address);
count++;
if (BRSetContains(wallet->usedAddrs, &address)) i = count;
}
if (addrs && i + gapLimit <= count) {
for (j = 0; j < gapLimit; j++) {
addrs[j] = addrChain[i + j];
}
}
// was addrChain moved to a new memory location?
if (addrChain == (internal ? wallet->internalChain : wallet->externalChain)) {
for (i = startCount; i < count; i++) {
BRSetAdd(wallet->allAddrs, &addrChain[i]);
}
}
else {
if (internal) wallet->internalChain = addrChain;
if (! internal) wallet->externalChain = addrChain;
BRSetClear(wallet->allAddrs); // clear and rebuild allAddrs
for (i = array_count(wallet->internalChain); i > 0; i--) {
BRSetAdd(wallet->allAddrs, &wallet->internalChain[i - 1]);
}
for (i = array_count(wallet->externalChain); i > 0; i--) {
BRSetAdd(wallet->allAddrs, &wallet->externalChain[i - 1]);
}
}
pthread_mutex_unlock(&wallet->lock);
return j;
}
// current wallet balance, not including transactions known to be invalid
uint64_t BRWalletBalance(BRWallet *wallet)
{
uint64_t balance;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
balance = wallet->balance;
pthread_mutex_unlock(&wallet->lock);
return balance;
}
// writes unspent outputs to utxos and returns the number of outputs written, or total number available if utxos is NULL
size_t BRWalletUTXOs(BRWallet *wallet, BRUTXO *utxos, size_t utxosCount)
{
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
if (! utxos || array_count(wallet->utxos) < utxosCount) utxosCount = array_count(wallet->utxos);
for (size_t i = 0; utxos && i < utxosCount; i++) {
utxos[i] = wallet->utxos[i];
}
pthread_mutex_unlock(&wallet->lock);
return utxosCount;
}
// writes transactions registered in the wallet, sorted by date, oldest first, to the given transactions array
// returns the number of transactions written, or total number available if transactions is NULL
size_t BRWalletTransactions(BRWallet *wallet, BRTransaction *transactions[], size_t txCount)
{
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
if (! transactions || array_count(wallet->transactions) < txCount) txCount = array_count(wallet->transactions);
for (size_t i = 0; transactions && i < txCount; i++) {
transactions[i] = wallet->transactions[i];
}
pthread_mutex_unlock(&wallet->lock);
return txCount;
}
// writes transactions registered in the wallet, and that were unconfirmed before blockHeight, to the transactions array
// returns the number of transactions written, or total number available if transactions is NULL
size_t BRWalletTxUnconfirmedBefore(BRWallet *wallet, BRTransaction *transactions[], size_t txCount,
uint32_t blockHeight)
{
size_t total, n = 0;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
total = array_count(wallet->transactions);
while (n < total && wallet->transactions[(total - n) - 1]->blockHeight >= blockHeight) n++;
if (! transactions || n < txCount) txCount = n;
for (size_t i = 0; transactions && i < txCount; i++) {
transactions[i] = wallet->transactions[(total - n) + i];
}
pthread_mutex_unlock(&wallet->lock);
return txCount;
}
// total amount spent from the wallet (exluding change)
uint64_t BRWalletTotalSent(BRWallet *wallet)
{
uint64_t totalSent;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
totalSent = wallet->totalSent;
pthread_mutex_unlock(&wallet->lock);
return totalSent;
}
// total amount received by the wallet (exluding change)
uint64_t BRWalletTotalReceived(BRWallet *wallet)
{
uint64_t totalReceived;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
totalReceived = wallet->totalReceived;
pthread_mutex_unlock(&wallet->lock);
return totalReceived;
}
// fee-per-kb of transaction size to use when creating a transaction
uint64_t BRWalletFeePerKb(BRWallet *wallet)
{
uint64_t feePerKb;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
feePerKb = wallet->feePerKb;
pthread_mutex_unlock(&wallet->lock);
return feePerKb;
}
void BRWalletSetFeePerKb(BRWallet *wallet, uint64_t feePerKb)
{
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
wallet->feePerKb = feePerKb;
pthread_mutex_unlock(&wallet->lock);
}
// returns the first unused external address
BRAddress BRWalletReceiveAddress(BRWallet *wallet)
{
BRAddress addr = BR_ADDRESS_NONE;
BRWalletUnusedAddrs(wallet, &addr, 1, 0);
return addr;
}
// writes all addresses previously genereated with BRWalletUnusedAddrs() to addrs
// returns the number addresses written, or total number available if addrs is NULL
size_t BRWalletAllAddrs(BRWallet *wallet, BRAddress addrs[], size_t addrsCount)
{
size_t i, internalCount = 0, externalCount = 0;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
internalCount = (! addrs || array_count(wallet->internalChain) < addrsCount) ?
array_count(wallet->internalChain) : addrsCount;
for (i = 0; addrs && i < internalCount; i++) {
addrs[i] = wallet->internalChain[i];
}
externalCount = (! addrs || array_count(wallet->externalChain) < addrsCount - internalCount) ?
array_count(wallet->externalChain) : addrsCount - internalCount;
for (i = 0; addrs && i < externalCount; i++) {
addrs[internalCount + i] = wallet->externalChain[i];
}
pthread_mutex_unlock(&wallet->lock);
return internalCount + externalCount;
}
// true if the address was previously generated by BRWalletUnusedAddrs() (even if it's now used)
int BRWalletContainsAddress(BRWallet *wallet, const char *addr)
{
int r = 0;
assert(wallet != NULL);
assert(addr != NULL);
pthread_mutex_lock(&wallet->lock);
if (addr) r = BRSetContains(wallet->allAddrs, addr);
pthread_mutex_unlock(&wallet->lock);
return r;
}
// true if the address was previously used as an output in any wallet transaction
int BRWalletAddressIsUsed(BRWallet *wallet, const char *addr)
{
int r = 0;
assert(wallet != NULL);
assert(addr != NULL);
pthread_mutex_lock(&wallet->lock);
if (addr) r = BRSetContains(wallet->usedAddrs, addr);
pthread_mutex_unlock(&wallet->lock);
return r;
}
// returns an unsigned transaction that sends the specified amount from the wallet to the given address
// result must be freed by calling BRTransactionFree()
BRTransaction *BRWalletCreateTransaction(BRWallet *wallet, uint64_t amount, const char *addr)
{
BRTxOutput o = BR_TX_OUTPUT_NONE;
assert(wallet != NULL);
assert(amount > 0);
assert(addr != NULL && BRAddressIsValid(addr));
o.amount = amount;
BRTxOutputSetAddress(&o, addr);
return BRWalletCreateTxForOutputs(wallet, &o, 1);
}
// returns an unsigned transaction that satisifes the given transaction outputs
// result must be freed by calling BRTransactionFree()
BRTransaction *BRWalletCreateTxForOutputs(BRWallet *wallet, const BRTxOutput outputs[], size_t outCount)
{
BRTransaction *tx, *transaction = BRTransactionNew();
uint64_t feeAmount, amount = 0, balance = 0, minAmount;
size_t i, j, cpfpSize = 0;
BRUTXO *o;
BRAddress addr = BR_ADDRESS_NONE;
assert(wallet != NULL);
assert(outputs != NULL && outCount > 0);
for (i = 0; outputs && i < outCount; i++) {
assert(outputs[i].script != NULL && outputs[i].scriptLen > 0);
BRTransactionAddOutput(transaction, outputs[i].amount, outputs[i].script, outputs[i].scriptLen);
amount += outputs[i].amount;
}
minAmount = BRWalletMinOutputAmount(wallet);
pthread_mutex_lock(&wallet->lock);
feeAmount = _txFee(wallet->feePerKb, BRTransactionSize(transaction) + TX_OUTPUT_SIZE);
// TODO: use up all UTXOs for all used addresses to avoid leaving funds in addresses whose public key is revealed
// TODO: avoid combining addresses in a single transaction when possible to reduce information leakage
// TODO: use up UTXOs received from any of the output scripts that this transaction sends funds to, to mitigate an
// attacker double spending and requesting a refund
for (i = 0; i < array_count(wallet->utxos); i++) {
o = &wallet->utxos[i];
tx = BRSetGet(wallet->allTx, o);
if (! tx || o->n >= tx->outCount) continue;
BRTransactionAddInput(transaction, tx->txHash, o->n, tx->outputs[o->n].amount,
tx->outputs[o->n].script, tx->outputs[o->n].scriptLen, NULL, 0, TXIN_SEQUENCE);
if (BRTransactionSize(transaction) + TX_OUTPUT_SIZE > TX_MAX_SIZE) { // transaction size-in-bytes too large
BRTransactionFree(transaction);
transaction = NULL;
// check for sufficient total funds before building a smaller transaction
if (wallet->balance < amount + _txFee(wallet->feePerKb, 10 + array_count(wallet->utxos)*TX_INPUT_SIZE +
(outCount + 1)*TX_OUTPUT_SIZE + cpfpSize)) break;
pthread_mutex_unlock(&wallet->lock);
if (outputs[outCount - 1].amount > amount + feeAmount + minAmount - balance) {
BRTxOutput newOutputs[outCount];
for (j = 0; j < outCount; j++) {
newOutputs[j] = outputs[j];
}
newOutputs[outCount - 1].amount -= amount + feeAmount - balance; // reduce last output amount
transaction = BRWalletCreateTxForOutputs(wallet, newOutputs, outCount);
}
else transaction = BRWalletCreateTxForOutputs(wallet, outputs, outCount - 1); // remove last output
balance = amount = feeAmount = 0;
pthread_mutex_lock(&wallet->lock);
break;
}
balance += tx->outputs[o->n].amount;
// // size of unconfirmed, non-change inputs for child-pays-for-parent fee
// // don't include parent tx with more than 10 inputs or 10 outputs
// if (tx->blockHeight == TX_UNCONFIRMED && tx->inCount <= 10 && tx->outCount <= 10 &&
// ! _BRWalletTxIsSend(wallet, tx)) cpfpSize += BRTransactionSize(tx);
// fee amount after adding a change output
feeAmount = _txFee(wallet->feePerKb, BRTransactionSize(transaction) + TX_OUTPUT_SIZE + cpfpSize);
// increase fee to round off remaining wallet balance to nearest 100 satoshi
if (wallet->balance > amount + feeAmount) feeAmount += (wallet->balance - (amount + feeAmount)) % 100;
if (balance == amount + feeAmount || balance >= amount + feeAmount + minAmount) break;
}
pthread_mutex_unlock(&wallet->lock);
if (transaction && (outCount < 1 || balance < amount + feeAmount)) { // no outputs/insufficient funds
BRTransactionFree(transaction);
transaction = NULL;
}
else if (transaction && balance - (amount + feeAmount) >= minAmount) { // add change output
BRWalletUnusedAddrs(wallet, &addr, 1, 1);
uint8_t script[BRAddressScriptPubKey(NULL, 0, addr.s)];
size_t scriptLen = BRAddressScriptPubKey(script, sizeof(script), addr.s);
BRTransactionAddOutput(transaction, balance - (amount + feeAmount), script, scriptLen);
BRTransactionShuffleOutputs(transaction);
}
return transaction;
}
// signs any inputs in tx that can be signed using private keys from the wallet
// forkId is 0 for bitcoin, 0x40 for b-cash
// seed is the master private key (wallet seed) corresponding to the master public key given when the wallet was created
// returns true if all inputs were signed, or false if there was an error or not all inputs were able to be signed
int BRWalletSignTransaction(BRWallet *wallet, BRTransaction *tx, int forkId, const void *seed, size_t seedLen)
{
uint32_t j, internalIdx[tx->inCount], externalIdx[tx->inCount];
size_t i, internalCount = 0, externalCount = 0;
int r = 0;
assert(wallet != NULL);
assert(tx != NULL);
pthread_mutex_lock(&wallet->lock);
for (i = 0; tx && i < tx->inCount; i++) {
for (j = (uint32_t)array_count(wallet->internalChain); j > 0; j--) {
if (BRAddressEq(tx->inputs[i].address, &wallet->internalChain[j - 1])) internalIdx[internalCount++] = j - 1;
}
for (j = (uint32_t)array_count(wallet->externalChain); j > 0; j--) {
if (BRAddressEq(tx->inputs[i].address, &wallet->externalChain[j - 1])) externalIdx[externalCount++] = j - 1;
}
}
pthread_mutex_unlock(&wallet->lock);
BRKey keys[internalCount + externalCount];
if (seed) {
BRBIP32PrivKeyList(keys, internalCount, seed, seedLen, SEQUENCE_INTERNAL_CHAIN, internalIdx);
BRBIP32PrivKeyList(&keys[internalCount], externalCount, seed, seedLen, SEQUENCE_EXTERNAL_CHAIN, externalIdx);
// TODO: XXX wipe seed callback
seed = NULL;
if (tx) r = BRTransactionSign(tx, forkId, keys, internalCount + externalCount);
for (i = 0; i < internalCount + externalCount; i++) BRKeyClean(&keys[i]);
}
else r = -1; // user canceled authentication
return r;
}
// true if the given transaction is associated with the wallet (even if it hasn't been registered)
int BRWalletContainsTransaction(BRWallet *wallet, const BRTransaction *tx)
{
int r = 0;
assert(wallet != NULL);
assert(tx != NULL);
pthread_mutex_lock(&wallet->lock);
if (tx) r = _BRWalletContainsTx(wallet, tx);
pthread_mutex_unlock(&wallet->lock);
return r;
}
// adds a transaction to the wallet, or returns false if it isn't associated with the wallet
int BRWalletRegisterTransaction(BRWallet *wallet, BRTransaction *tx)
{
int wasAdded = 0, r = 1;
assert(wallet != NULL);
assert(tx != NULL && BRTransactionIsSigned(tx));
if (tx && BRTransactionIsSigned(tx)) {
pthread_mutex_lock(&wallet->lock);
if (! BRSetContains(wallet->allTx, tx)) {
if (_BRWalletContainsTx(wallet, tx)) {
// TODO: verify signatures when possible
// TODO: handle tx replacement with input sequence numbers
// (for now, replacements appear invalid until confirmation)
BRSetAdd(wallet->allTx, tx);
_BRWalletInsertTx(wallet, tx);
_BRWalletUpdateBalance(wallet);
wasAdded = 1;
}
else { // keep track of unconfirmed non-wallet tx for invalid tx checks and child-pays-for-parent fees
// BUG: limit total non-wallet unconfirmed tx to avoid memory exhaustion attack
if (tx->blockHeight == TX_UNCONFIRMED) BRSetAdd(wallet->allTx, tx);
r = 0;
// BUG: XXX memory leak if tx is not added to wallet->allTx, and we can't just free it
}
}
pthread_mutex_unlock(&wallet->lock);
}
else r = 0;
if (wasAdded) {
// when a wallet address is used in a transaction, generate a new address to replace it
BRWalletUnusedAddrs(wallet, NULL, SEQUENCE_GAP_LIMIT_EXTERNAL, 0);
BRWalletUnusedAddrs(wallet, NULL, SEQUENCE_GAP_LIMIT_INTERNAL, 1);
if (wallet->balanceChanged) wallet->balanceChanged(wallet->callbackInfo, wallet->balance);
if (wallet->txAdded) wallet->txAdded(wallet->callbackInfo, tx);
}
return r;
}
// removes a tx from the wallet and calls BRTransactionFree() on it, along with any tx that depend on its outputs
void BRWalletRemoveTransaction(BRWallet *wallet, UInt256 txHash)
{
BRTransaction *tx, *t;
UInt256 *hashes = NULL;
int notifyUser = 0, recommendRescan = 0;
assert(wallet != NULL);
assert(! UInt256IsZero(txHash));
pthread_mutex_lock(&wallet->lock);
tx = BRSetGet(wallet->allTx, &txHash);
if (tx) {
array_new(hashes, 0);
for (size_t i = array_count(wallet->transactions); i > 0; i--) { // find depedent transactions
t = wallet->transactions[i - 1];
if (t->blockHeight < tx->blockHeight) break;
if (BRTransactionEq(tx, t)) continue;
for (size_t j = 0; j < t->inCount; j++) {
if (! UInt256Eq(t->inputs[j].txHash, txHash)) continue;
array_add(hashes, t->txHash);
break;
}
}
if (array_count(hashes) > 0) {
pthread_mutex_unlock(&wallet->lock);
for (size_t i = array_count(hashes); i > 0; i--) {
BRWalletRemoveTransaction(wallet, hashes[i - 1]);
}
BRWalletRemoveTransaction(wallet, txHash);
}
else {
BRSetRemove(wallet->allTx, tx);
for (size_t i = array_count(wallet->transactions); i > 0; i--) {
if (! BRTransactionEq(wallet->transactions[i - 1], tx)) continue;
array_rm(wallet->transactions, i - 1);
break;
}
_BRWalletUpdateBalance(wallet);
pthread_mutex_unlock(&wallet->lock);
// if this is for a transaction we sent, and it wasn't already known to be invalid, notify user
if (BRWalletAmountSentByTx(wallet, tx) > 0 && BRWalletTransactionIsValid(wallet, tx)) {
recommendRescan = notifyUser = 1;
for (size_t i = 0; i < tx->inCount; i++) { // only recommend a rescan if all inputs are confirmed
t = BRWalletTransactionForHash(wallet, tx->inputs[i].txHash);
if (t && t->blockHeight != TX_UNCONFIRMED) continue;
recommendRescan = 0;
break;
}
}
BRTransactionFree(tx);
if (wallet->balanceChanged) wallet->balanceChanged(wallet->callbackInfo, wallet->balance);
if (wallet->txDeleted) wallet->txDeleted(wallet->callbackInfo, txHash, notifyUser, recommendRescan);
}
array_free(hashes);
}
else pthread_mutex_unlock(&wallet->lock);
}
// returns the transaction with the given hash if it's been registered in the wallet
BRTransaction *BRWalletTransactionForHash(BRWallet *wallet, UInt256 txHash)
{
BRTransaction *tx;
assert(wallet != NULL);
assert(! UInt256IsZero(txHash));
pthread_mutex_lock(&wallet->lock);
tx = BRSetGet(wallet->allTx, &txHash);
pthread_mutex_unlock(&wallet->lock);
return tx;
}
// true if no previous wallet transaction spends any of the given transaction's inputs, and no inputs are invalid
int BRWalletTransactionIsValid(BRWallet *wallet, const BRTransaction *tx)
{
BRTransaction *t;
int r = 1;
assert(wallet != NULL);
assert(tx != NULL && BRTransactionIsSigned(tx));
// TODO: XXX attempted double spends should cause conflicted tx to remain unverified until they're confirmed
// TODO: XXX conflicted tx with the same wallet outputs should be presented as the same tx to the user
if (tx && tx->blockHeight == TX_UNCONFIRMED) { // only unconfirmed transactions can be invalid
pthread_mutex_lock(&wallet->lock);
if (! BRSetContains(wallet->allTx, tx)) {
for (size_t i = 0; r && i < tx->inCount; i++) {
if (BRSetContains(wallet->spentOutputs, &tx->inputs[i])) r = 0;
}
}
else if (BRSetContains(wallet->invalidTx, tx)) r = 0;
pthread_mutex_unlock(&wallet->lock);
for (size_t i = 0; r && i < tx->inCount; i++) {
t = BRWalletTransactionForHash(wallet, tx->inputs[i].txHash);
if (t && ! BRWalletTransactionIsValid(wallet, t)) r = 0;
}
}
return r;
}
// true if tx cannot be immediately spent (i.e. if it or an input tx can be replaced-by-fee)
int BRWalletTransactionIsPending(BRWallet *wallet, const BRTransaction *tx)
{
BRTransaction *t;
time_t now = time(NULL);
uint32_t blockHeight;
int r = 0;
assert(wallet != NULL);
assert(tx != NULL && BRTransactionIsSigned(tx));
pthread_mutex_lock(&wallet->lock);
blockHeight = wallet->blockHeight;
pthread_mutex_unlock(&wallet->lock);
if (tx && tx->blockHeight == TX_UNCONFIRMED) { // only unconfirmed transactions can be postdated
if (BRTransactionSize(tx) > TX_MAX_SIZE) r = 1; // check transaction size is under TX_MAX_SIZE
for (size_t i = 0; ! r && i < tx->inCount; i++) {
if (tx->inputs[i].sequence < UINT32_MAX - 1) r = 1; // check for replace-by-fee
if (tx->inputs[i].sequence < UINT32_MAX && tx->lockTime < TX_MAX_LOCK_HEIGHT &&
tx->lockTime > blockHeight + 1) r = 1; // future lockTime
if (tx->inputs[i].sequence < UINT32_MAX && tx->lockTime > now) r = 1; // future lockTime
}
for (size_t i = 0; ! r && i < tx->outCount; i++) { // check that no outputs are dust
if (tx->outputs[i].amount < TX_MIN_OUTPUT_AMOUNT) r = 1;
}
for (size_t i = 0; ! r && i < tx->inCount; i++) { // check if any inputs are known to be pending
t = BRWalletTransactionForHash(wallet, tx->inputs[i].txHash);
if (t && BRWalletTransactionIsPending(wallet, t)) r = 1;
}
}
return r;
}
// true if tx is considered 0-conf safe (valid and not pending, timestamp is greater than 0, and no unverified inputs)
int BRWalletTransactionIsVerified(BRWallet *wallet, const BRTransaction *tx)
{
BRTransaction *t;
int r = 1;
assert(wallet != NULL);
assert(tx != NULL && BRTransactionIsSigned(tx));
if (tx && tx->blockHeight == TX_UNCONFIRMED) { // only unconfirmed transactions can be unverified
if (tx->timestamp == 0 || ! BRWalletTransactionIsValid(wallet, tx) ||
BRWalletTransactionIsPending(wallet, tx)) r = 0;
for (size_t i = 0; r && i < tx->inCount; i++) { // check if any inputs are known to be unverified
t = BRWalletTransactionForHash(wallet, tx->inputs[i].txHash);
if (t && ! BRWalletTransactionIsVerified(wallet, t)) r = 0;
}
}
return r;
}
// set the block heights and timestamps for the given transactions
// use height TX_UNCONFIRMED and timestamp 0 to indicate a tx should remain marked as unverified (not 0-conf safe)
void BRWalletUpdateTransactions(BRWallet *wallet, const UInt256 txHashes[], size_t txCount, uint32_t blockHeight,
uint32_t timestamp)
{
BRTransaction *tx;
UInt256 hashes[txCount];
int needsUpdate = 0;
size_t i, j;
assert(wallet != NULL);
assert(txHashes != NULL || txCount == 0);
pthread_mutex_lock(&wallet->lock);
if (blockHeight > wallet->blockHeight) wallet->blockHeight = blockHeight;
for (i = 0, j = 0; txHashes && i < txCount; i++) {
tx = BRSetGet(wallet->allTx, &txHashes[i]);
if (! tx || (tx->blockHeight == blockHeight && tx->timestamp == timestamp)) continue;
tx->timestamp = timestamp;
tx->blockHeight = blockHeight;
if (_BRWalletContainsTx(wallet, tx)) {
hashes[j++] = txHashes[i];
if (BRSetContains(wallet->pendingTx, tx) || BRSetContains(wallet->invalidTx, tx)) needsUpdate = 1;
}
else if (blockHeight != TX_UNCONFIRMED) { // remove and free confirmed non-wallet tx
BRSetRemove(wallet->allTx, tx);
BRTransactionFree(tx);
}
}
if (needsUpdate) _BRWalletUpdateBalance(wallet);
pthread_mutex_unlock(&wallet->lock);
if (j > 0 && wallet->txUpdated) wallet->txUpdated(wallet->callbackInfo, hashes, j, blockHeight, timestamp);
}
// marks all transactions confirmed after blockHeight as unconfirmed (useful for chain re-orgs)
void BRWalletSetTxUnconfirmedAfter(BRWallet *wallet, uint32_t blockHeight)
{
size_t i, j, count;
assert(wallet != NULL);
pthread_mutex_lock(&wallet->lock);
wallet->blockHeight = blockHeight;
count = i = array_count(wallet->transactions);
while (i > 0 && wallet->transactions[i - 1]->blockHeight > blockHeight) i--;
count -= i;
UInt256 hashes[count];
for (j = 0; j < count; j++) {
wallet->transactions[i + j]->blockHeight = TX_UNCONFIRMED;
hashes[j] = wallet->transactions[i + j]->txHash;
}
if (count > 0) _BRWalletUpdateBalance(wallet);
pthread_mutex_unlock(&wallet->lock);
if (count > 0 && wallet->txUpdated) wallet->txUpdated(wallet->callbackInfo, hashes, count, TX_UNCONFIRMED, 0);
}
// returns the amount received by the wallet from the transaction (total outputs to change and/or receive addresses)
uint64_t BRWalletAmountReceivedFromTx(BRWallet *wallet, const BRTransaction *tx)
{
uint64_t amount = 0;
assert(wallet != NULL);
assert(tx != NULL);
pthread_mutex_lock(&wallet->lock);
// TODO: don't include outputs below TX_MIN_OUTPUT_AMOUNT
for (size_t i = 0; tx && i < tx->outCount; i++) {