-
Notifications
You must be signed in to change notification settings - Fork 197
/
wallets.py
2934 lines (2534 loc) · 128 KB
/
wallets.py
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
# -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# WALLETS - HD wallet Class for key and transaction management
# © 2018 April - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import numbers
from copy import deepcopy
import struct
from sqlalchemy import or_
from itertools import groupby
from operator import itemgetter
from bitcoinlib.db import *
from bitcoinlib.encoding import pubkeyhash_to_addr, to_hexstring, script_to_pubkeyhash, to_bytes
from bitcoinlib.keys import HDKey, check_network_and_key
from bitcoinlib.networks import Network, DEFAULT_NETWORK
from bitcoinlib.services.services import Service
from bitcoinlib.mnemonic import Mnemonic
from bitcoinlib.transactions import Transaction, serialize_multisig_redeemscript, Output, Input, SIGHASH_ALL
_logger = logging.getLogger(__name__)
class WalletError(Exception):
"""
Handle Wallet class Exceptions
"""
def __init__(self, msg=''):
self.msg = msg
_logger.error(msg)
def __str__(self):
return self.msg
def wallets_list(databasefile=DEFAULT_DATABASE):
"""
List Wallets from database
:param databasefile: Location of Sqlite database. Leave empty to use default
:type databasefile: str
:return dict: Dictionary of wallets defined in database
"""
session = DbInit(databasefile=databasefile).session
wallets = session.query(DbWallet).all()
wlst = []
for w in wallets:
wlst.append({
'id': w.id,
'name': w.name,
'owner': w.owner,
'network': w.network_name,
'purpose': w.purpose,
'scheme': w.scheme,
'main_key_id': w.main_key_id,
'parent_id': w.parent_id,
})
session.close()
return wlst
def wallet_exists(wallet, databasefile=DEFAULT_DATABASE):
"""
Check if Wallets is defined in database
:param wallet: Wallet ID as integer or Wallet Name as string
:type wallet: int, str
:param databasefile: Location of Sqlite database. Leave empty to use default
:type databasefile: str
:return bool: True if wallet exists otherwise False
"""
if wallet in [x['name'] for x in wallets_list(databasefile)]:
return True
if isinstance(wallet, int) and wallet in [x['id'] for x in wallets_list(databasefile)]:
return True
return False
def wallet_create_or_open(name, key='', owner='', network=None, account_id=0, purpose=44, scheme='bip44',
parent_id=None, sort_keys=False, password='', databasefile=DEFAULT_DATABASE):
"""
Create a wallet with specified options if it doesn't exist, otherwise just open
See Wallets class create method for option documentation
"""
if wallet_exists(name, databasefile=databasefile):
return HDWallet(name, databasefile=databasefile)
else:
return HDWallet.create(name, key, owner, network, account_id, purpose, scheme, parent_id, sort_keys,
password, databasefile)
def wallet_create_or_open_multisig(
name, key_list, sigs_required=None, owner='', network=None, account_id=0,
purpose=45, multisig_compressed=True, sort_keys=False, databasefile=DEFAULT_DATABASE):
"""
Create a wallet with specified options if it doesn't exist, otherwise just open
See Wallets class create method for option documentation
"""
if wallet_exists(name, databasefile=databasefile):
return HDWallet(name, databasefile=databasefile)
else:
return HDWallet.create_multisig(name, key_list, sigs_required, owner, network, account_id, purpose,
multisig_compressed, sort_keys, databasefile)
def wallet_delete(wallet, databasefile=DEFAULT_DATABASE, force=False):
"""
Delete wallet and associated keys and transactions from the database. If wallet has unspent outputs it raises a
WalletError exception unless 'force=True' is specified
:param wallet: Wallet ID as integer or Wallet Name as string
:type wallet: int, str
:param databasefile: Location of Sqlite database. Leave empty to use default
:type databasefile: str
:param force: If set to True wallet will be deleted even if unspent outputs are found. Default is False
:type force: bool
:return int: Number of rows deleted, so 1 if succesfull
"""
session = DbInit(databasefile=databasefile).session
if isinstance(wallet, int) or wallet.isdigit():
w = session.query(DbWallet).filter_by(id=wallet)
else:
w = session.query(DbWallet).filter_by(name=wallet)
if not w or not w.first():
raise WalletError("Wallet '%s' not found" % wallet)
wallet_id = w.first().id
# Delete keys from this wallet and update transactions (remove key_id)
ks = session.query(DbKey).filter_by(wallet_id=wallet_id)
for k in ks:
if not force and k.balance:
raise WalletError("Key %d (%s) still has unspent outputs. Use 'force=True' to delete this wallet" %
(k.id, k.address))
session.query(DbTransactionOutput).filter_by(key_id=k.id).update({DbTransactionOutput.key_id: None})
session.query(DbTransactionInput).filter_by(key_id=k.id).update({DbTransactionInput.key_id: None})
session.query(DbKeyMultisigChildren).filter_by(parent_id=k.id).delete()
session.query(DbKeyMultisigChildren).filter_by(child_id=k.id).delete()
ks.delete()
# Delete transactions from this wallet (remove wallet_id)
session.query(DbTransaction).filter_by(wallet_id=wallet_id).update({DbTransaction.wallet_id: None})
res = w.delete()
session.commit()
session.close()
# Delete co-signer wallets if this is a multisig wallet
for cw in session.query(DbWallet).filter_by(parent_id=wallet_id).all():
wallet_delete(cw.id, databasefile=databasefile, force=force)
_logger.info("Wallet '%s' deleted" % wallet)
return res
def wallet_empty(wallet, databasefile=DEFAULT_DATABASE):
session = DbInit(databasefile=databasefile).session
if isinstance(wallet, int) or wallet.isdigit():
w = session.query(DbWallet).filter_by(id=wallet)
else:
w = session.query(DbWallet).filter_by(name=wallet)
if not w or not w.first():
raise WalletError("Wallet '%s' not found" % wallet)
wallet_id = w.first().id
# Delete keys from this wallet and update transactions (remove key_id)
ks = session.query(DbKey).filter(DbKey.wallet_id == wallet_id, DbKey.depth > 3)
for k in ks:
session.query(DbTransactionOutput).filter_by(key_id=k.id).update({DbTransactionOutput.key_id: None})
session.query(DbTransactionInput).filter_by(key_id=k.id).update({DbTransactionInput.key_id: None})
session.query(DbKeyMultisigChildren).filter_by(parent_id=k.id).delete()
session.query(DbKeyMultisigChildren).filter_by(child_id=k.id).delete()
ks.delete()
# Delete transactions from this wallet (remove wallet_id)
session.query(DbTransaction).filter_by(wallet_id=wallet_id).update({DbTransaction.wallet_id: None})
session.commit()
session.close()
_logger.info("All keys and transactions from wallet '%s' deleted" % wallet)
return True
def wallet_delete_if_exists(wallet, databasefile=DEFAULT_DATABASE, force=False):
"""
Delete wallet and associated keys from the database. If wallet has unspent outputs it raises a WalletError exception
unless 'force=True' is specified. If wallet wallet does not exist return False
:param wallet: Wallet ID as integer or Wallet Name as string
:type wallet: int, str
:param databasefile: Location of Sqlite database. Leave empty to use default
:type databasefile: str
:param force: If set to True wallet will be deleted even if unspent outputs are found. Default is False
:type force: bool
:return int: Number of rows deleted, so 1 if succesfull
"""
if wallet_exists(wallet, databasefile):
return wallet_delete(wallet, databasefile, force)
return False
def normalize_path(path):
""" Normalize BIP0044 key path for HD keys. Using single quotes for hardened keys
:param path: BIP0044 key path
:type path: str
:return str: Normalized BIP0044 key path with single quotes
"""
levels = path.split("/")
npath = ""
for level in levels:
if not level:
raise WalletError("Could not parse path. Index is empty.")
nlevel = level
if level[-1] in "'HhPp":
nlevel = level[:-1] + "'"
npath += nlevel + "/"
if npath[-1] == "/":
npath = npath[:-1]
return npath
def parse_bip44_path(path):
"""
Assumes a correct BIP0044 path and returns a dictionary with path items. See Bitcoin improvement proposals
BIP0043 and BIP0044.
Specify path in this format: m / purpose' / cointype' / account' / change / address_index.
Path length must be between 1 and 6 (Depth between 0 and 5)
:param path: BIP0044 path as string, with backslash (/) seperator.
:type path: str
:return dict: Dictionary with path items: isprivate, purpose, cointype, account, change and address_index
"""
pathl = normalize_path(path).split('/')
if not 0 < len(pathl) <= 6:
raise WalletError("Not a valid BIP0044 path. Path length (depth) must be between 1 and 6 not %d" % len(pathl))
return {
'isprivate': True if pathl[0] == 'm' else False,
'purpose': '' if len(pathl) < 2 else pathl[1],
'cointype': '' if len(pathl) < 3 else pathl[2],
'account': '' if len(pathl) < 4 else pathl[3],
'change': '' if len(pathl) < 5 else pathl[4],
'address_index': '' if len(pathl) < 6 else pathl[5],
}
class HDWalletKey:
"""
Normally only used as attribute of HDWallet class. Contains HDKey object and extra information such as path and
balance.
All HDWalletKey are stored in a database
"""
@staticmethod
def from_key(name, wallet_id, session, key='', account_id=0, network=None, change=0,
purpose=44, parent_id=0, path='m', key_type=None):
"""
Create HDWalletKey from a HDKey object or key
:param name: New key name
:type name: str
:param wallet_id: ID of wallet where to store key
:type wallet_id: int
:param session: Required Sqlalchemy Session object
:type session: sqlalchemy.orm.session.Session
:param key: Optional key in any format accepted by the HDKey class
:type key: str, int, byte, bytearray, HDKey
:param account_id: Account ID for specified key, default is 0
:type account_id: int
:param network: Network of specified key
:type network: str
:param change: Use 0 for normal key, and 1 for change key (for returned payments)
:type change: int
:param purpose: BIP0044 purpose field, default is 44
:type purpose: int
:param parent_id: Key ID of parent, default is 0 (no parent)
:type parent_id: int
:param path: BIP0044 path of given key, default is 'm' (masterkey)
:type path: str
:param key_type: Type of key, single or BIP44 type
:type key_type: str
:return HDWalletKey: HDWalletKey object
"""
if isinstance(key, HDKey):
k = key
else:
if network is None:
network = DEFAULT_NETWORK
k = HDKey(import_key=key, network=network)
keyexists = session.query(DbKey).filter(DbKey.wallet_id == wallet_id, DbKey.wif == k.wif()).first()
if keyexists:
_logger.warning("Key %s already exists" % (key or k.wif()))
return HDWalletKey(keyexists.id, session, k)
if key_type != 'single' and k.depth != len(path.split('/'))-1:
if path == 'm' and k.depth == 3:
# Create path when importing new account-key
nw = Network(network)
networkcode = nw.bip44_cointype
path = "m/%d'/%s'/%d'" % (purpose, networkcode, account_id)
else:
raise WalletError("Key depth of %d does not match path length of %d for path %s" %
(k.depth, len(path.split('/')) - 1, path))
wk = session.query(DbKey).filter(DbKey.wallet_id == wallet_id,
or_(DbKey.public == k.public_hex,
DbKey.wif == k.wif())).first()
if wk:
return HDWalletKey(wk.id, session, k)
nk = DbKey(name=name, wallet_id=wallet_id, public=k.public_hex, private=k.private_hex, purpose=purpose,
account_id=account_id, depth=k.depth, change=change, address_index=k.child_index,
wif=k.wif(), address=k.key.address(), parent_id=parent_id, compressed=k.compressed,
is_private=k.isprivate, path=path, key_type=key_type, network_name=network)
session.add(nk)
session.commit()
return HDWalletKey(nk.id, session, k)
def __init__(self, key_id, session, hdkey_object=None):
"""
Initialize HDWalletKey with specified ID, get information from database.
:param key_id: ID of key as mentioned in database
:type key_id: int
:param session: Required Sqlalchemy Session object
:type session: sqlalchemy.orm.session.Session
:param hdkey_object: Optional HDKey object
:type hdkey_object: HDKey
"""
wk = session.query(DbKey).filter_by(id=key_id).first()
if wk:
self._dbkey = wk
self._hdkey_object = hdkey_object
self.key_id = key_id
self.name = wk.name
self.wallet_id = wk.wallet_id
# self.key_hex = wk.key
self.key_public = wk.public
self.key_private = wk.private
self.account_id = wk.account_id
self.change = wk.change
self.address_index = wk.address_index
self.wif = wk.wif
self.address = wk.address
self._balance = wk.balance
self.purpose = wk.purpose
self.parent_id = wk.parent_id
self.is_private = wk.is_private
self.path = wk.path
self.wallet = wk.wallet
self.network_name = wk.network_name
if not self.network_name:
self.network_name = wk.wallet.network_name
self.network = Network(self.network_name)
self.depth = wk.depth
self.key_type = wk.key_type
self.compressed = wk.compressed
else:
raise WalletError("Key with id %s not found" % key_id)
def __repr__(self):
return "<HDWalletKey(key_id=%d, name=%s, wif=%s, path=%s)>" % (self.key_id, self.name, self.wif, self.path)
def key(self):
"""
Get HDKey object for current HDWalletKey
:return HDKey:
"""
if self._hdkey_object is None:
self._hdkey_object = HDKey(import_key=self.wif, network=self.network_name)
return self._hdkey_object
def balance(self, fmt=''):
"""
Get total of unspent outputs
:param fmt: Specify 'string' to return a string in currency format
:type fmt: str
:return float, str: Key balance
"""
if fmt == 'string':
return self.network.print_value(self._balance)
else:
return self._balance
def fullpath(self, change=None, address_index=None, max_depth=5):
"""
Full BIP0044 key path:
- m / purpose' / coin_type' / account' / change / address_index
:param change: Normal = 0, change =1
:type change: int
:param address_index: Index number of address (path depth 5)
:type address_index: int
:param max_depth: Maximum depth of output path. I.e. type 3 for account path
:type max_depth: int
:return list: Current key path
"""
if change is None:
change = self.change
if address_index is None:
address_index = self.address_index
if self.is_private:
p = ["m"]
else:
p = ["M"]
p.append(str(self.purpose) + "'")
p.append(str(self.network.bip44_cointype) + "'")
p.append(str(self.account_id) + "'")
p.append(str(change))
p.append(str(address_index))
return p[:max_depth]
def dict(self):
"""
Return current key information as dictionary
"""
return {
'id': self.key_id,
'key_type': self.key_type,
'is_private': self.is_private,
'name': self.name,
'key_private': self.key_private,
'key_public': self.key_public,
'wif': self.wif,
'account_id': self.account_id,
'parent_id': self.parent_id,
'depth': self.depth,
'change': self.change,
'address_index': self.address_index,
'address': self.address,
'path': self.path,
'balance': self.balance(),
'balance_str': self.balance(fmt='string')
}
class HDWalletTransaction(Transaction):
"""
Normally only used as attribute of HDWallet class. Child of Transaction object with extra reference to
wallet and database object.
All HDWalletTransaction items are stored in a database
"""
def __init__(self, hdwallet, *args, **kwargs):
"""
Initialize HDWalletTransaction object with reference to a HDWallet object
:param hdwallet: HDWallet object, wallet name or ID
:type hdWallet: HDwallet, str, int
:param args: Arguments for HDWallet parent class
:type args: args
:param kwargs: Keyword arguments for HDWallet parent class
:type kwargs: kwargs
"""
assert isinstance(hdwallet, HDWallet)
self.hdwallet = hdwallet
self.pushed = False
self.error = None
Transaction.__init__(self, *args, **kwargs)
def __repr__(self):
return "<HDWalletTransaction(input_count=%d, output_count=%d, status=%s, network=%s)>" % \
(len(self.inputs), len(self.outputs), self.status, self.network.network_name)
@classmethod
def from_transaction(cls, hdwallet, t):
"""
Create HDWalletTransaction object from Transaction object
:param hdwallet: HDWallet object, wallet name or ID
:type hdwallet: HDwallet, str, int
:param t: Specify Transaction object
:type t: Transaction
:return HDWalletClass:
"""
return cls(hdwallet=hdwallet, inputs=t.inputs, outputs=t.outputs, locktime=t.locktime, version=t.version,
network=t.network.network_name, fee=t.fee, fee_per_kb=t.fee_per_kb, size=t.size,
hash=t.hash, date=t.date, confirmations=t.confirmations, block_height=t.block_height,
block_hash=t.block_hash, input_total=t.input_total, output_total=t.output_total,
rawtx=t.rawtx, status=t.status, coinbase=t.coinbase, verified=t.verified, flag=t.flag)
def sign(self, keys=None, index_n=0, hash_type=SIGHASH_ALL):
"""
Sign this transaction. Use existing keys from wallet or use keys argument for extra keys.
:param keys: Extra private keys to sign the transaction
:type keys: HDKey, str
:param index_n: Transaction index_n to sign
:type index_n: int
:param hash_type: Hashtype to use, default is SIGHASH_ALL
:type hash_type: int
:return bool: True is successfully signed
"""
priv_key_list_arg = []
if keys:
if not isinstance(keys, list):
keys = [keys]
for priv_key in keys:
if isinstance(priv_key, HDKey):
priv_key_list_arg.append(priv_key)
else:
priv_key_list_arg.append(HDKey(priv_key))
for ti in self.inputs:
priv_key_list = deepcopy(priv_key_list_arg)
for k in ti.keys:
if k.isprivate:
if isinstance(k, HDKey):
hdkey = k
else:
hdkey = HDKey(k)
if hdkey not in priv_key_list:
priv_key_list.append(k)
elif self.hdwallet.cosigner:
# Check if private key is available in wallet
cosign_wallet_ids = [w.wallet_id for w in self.hdwallet.cosigner]
db_pk = self.hdwallet._session.query(DbKey).filter_by(public=k.public_hex, is_private=True). \
filter(DbKey.wallet_id.in_(cosign_wallet_ids + [self.hdwallet.wallet_id])).first()
if db_pk:
priv_key_list.append(HDKey(db_pk.wif))
Transaction.sign(self, priv_key_list, ti.index_n, hash_type)
self.verify()
self.error = ""
return True
def send(self, offline=False):
"""
Verify and push transaction to network. Update UTXO's in database after successfull send
:param offline: Just return the transaction object and do not send it when offline = True. Default is False
:type offline: bool
:return bool: Returns True if succesfully pushed to the network
"""
self.error = None
# if not self.verified:
# self.sign()
if not self.verified and not self.verify():
self.error = "Cannot verify transaction"
return False
if offline:
return False
srv = Service(network=self.network.network_name)
res = srv.sendrawtransaction(self.raw_hex())
if not res:
self.error = "Cannot send transaction. %s" % srv.errors
return False
if 'txid' in res:
_logger.info("Successfully pushed transaction, result: %s" % res)
self.hash = res['txid']
self.status = 'unconfirmed'
self.confirmations = 0
self.pushed = True
self.save()
# Update db: Update spent UTXO's, add transaction to database
for inp in self.inputs:
tx_hash = to_hexstring(inp.prev_hash)
utxos = self.hdwallet._session.query(DbTransactionOutput).join(DbTransaction).\
filter(DbTransaction.hash == tx_hash,
DbTransactionOutput.output_n == inp.output_n_int,
DbTransactionOutput.spent.op("IS")(False)).all()
for u in utxos:
u.spent = True
self.hdwallet._session.commit()
self.hdwallet._balance_update(network=self.network.network_name)
return True
return False
def save(self):
"""
Save this transaction to database
:return int: Transaction ID
"""
sess = self.hdwallet._session
# If tx_hash is unknown add it to database, else update
db_tx_query = sess.query(DbTransaction). \
filter(DbTransaction.wallet_id == self.hdwallet.wallet_id, DbTransaction.hash == self.hash)
db_tx = db_tx_query.scalar()
if not db_tx:
db_tx_query = sess.query(DbTransaction). \
filter(DbTransaction.wallet_id.is_(None), DbTransaction.hash == self.hash)
db_tx = db_tx_query.first()
if db_tx:
db_tx.wallet_id = self.hdwallet.wallet_id
if not db_tx:
new_tx = DbTransaction(
wallet_id=self.hdwallet.wallet_id, hash=self.hash, block_height=self.block_height,
size=self.size, confirmations=self.confirmations, date=self.date, fee=self.fee, status=self.status,
input_total=self.input_total, output_total=self.output_total, network_name=self.network.network_name,
raw=self.raw_hex(), block_hash=self.block_hash)
sess.add(new_tx)
sess.commit()
tx_id = new_tx.id
else:
tx_id = db_tx.id
db_tx.block_height = self.block_height if self.block_height else db_tx.block_height
db_tx.confirmations = self.confirmations if self.confirmations else db_tx.confirmations
db_tx.date = self.date if self.date else db_tx.date
db_tx.fee = self.fee if self.fee else db_tx.fee
db_tx.status = self.status if self.status else db_tx.status
db_tx.input_total = self.input_total if self.input_total else db_tx.input_total
db_tx.output_total = self.output_total if self.output_total else db_tx.output_total
db_tx.network_name = self.network.network_name if self.network.network_name else db_tx.network_name
sess.commit()
assert tx_id
for ti in self.inputs:
tx_key = sess.query(DbKey).filter_by(wallet_id=self.hdwallet.wallet_id, address=ti.address).scalar()
key_id = None
if tx_key:
key_id = tx_key.id
tx_key.used = True
tx_input = sess.query(DbTransactionInput). \
filter_by(transaction_id=tx_id, index_n=ti.index_n).scalar()
if not tx_input:
index_n = ti.index_n
if index_n is None:
last_index_n = sess.query(DbTransactionInput.index_n).\
filter_by(transaction_id=tx_id). \
order_by(DbTransactionInput.index_n.desc()).first()
index_n = 0
if last_index_n:
index_n = last_index_n[0] + 1
new_tx_item = DbTransactionInput(
transaction_id=tx_id, output_n=ti.output_n_int, key_id=key_id, value=ti.value,
prev_hash=to_hexstring(ti.prev_hash), index_n=index_n, double_spend=ti.double_spend,
script=to_hexstring(ti.unlocking_script), script_type=ti.script_type)
sess.add(new_tx_item)
elif key_id:
tx_input.key_id = key_id
if ti.value:
tx_input.value = ti.value
if ti.prev_hash:
tx_input.prev_hash = to_hexstring(ti.prev_hash)
if ti.unlocking_script:
tx_input.script = to_hexstring(ti.unlocking_script)
sess.commit()
for to in self.outputs:
tx_key = sess.query(DbKey).\
filter_by(wallet_id=self.hdwallet.wallet_id, address=to.address).scalar()
key_id = None
if tx_key:
key_id = tx_key.id
tx_key.used = True
spent = to.spent
tx_output = sess.query(DbTransactionOutput). \
filter_by(transaction_id=tx_id, output_n=to.output_n).scalar()
if not tx_output:
new_tx_item = DbTransactionOutput(
transaction_id=tx_id, output_n=to.output_n, key_id=key_id, value=to.value, spent=spent,
script=to_hexstring(to.lock_script), script_type=to.script_type)
sess.add(new_tx_item)
elif key_id:
tx_output.key_id = key_id
tx_output.spent = spent if spent is not None else tx_output.spent
sess.commit()
return tx_id
def info(self):
"""
Print Wallet transaction information to standard output. Include send information.
"""
Transaction.info(self)
print("Pushed to network: %s" % self.pushed)
print("Wallet: %s" % self.hdwallet.name)
self.pushed = False
if self.error:
print("Send errors: %s" % self.error)
class HDWallet:
"""
Class to create and manage keys Using the BIP0044 Hierarchical Deterministic wallet definitions, so you can
use one Masterkey to generate as much child keys as you want in a structured manner.
You can import keys in many format such as WIF or extended WIF, bytes, hexstring, seeds or private key integer.
For the Bitcoin network, Litecoin or any other network you define in the settings.
Easily send and receive transactions. Compose transactions automatically or select unspent outputs.
Each wallet name must be unique and can contain only one cointype and purpose, but practically unlimited
accounts and addresses.
"""
@classmethod
def create(cls, name, key='', owner='', network=None, account_id=0, purpose=44, scheme='bip44', parent_id=None,
sort_keys=True, password='', databasefile=None):
"""
Create HDWallet and insert in database. Generate masterkey or import key when specified.
Please mention account_id if you are using multiple accounts.
:param name: Unique name of this Wallet
:type name: str
:param key: Masterkey to use for this wallet. Will be automatically created if not specified. Can contain all key formats accepted by the HDKey object, a HDKey object or BIP39 passphrase
:type key: str, bytes, int, bytearray
:param owner: Wallet owner for your own reference
:type owner: str
:param network: Network name, use default if not specified
:type network: str
:param account_id: Account ID, default is 0
:type account_id: int
:param purpose: BIP44 purpose field, default is 44
:type purpose: int
:param scheme: Key structure type, i.e. BIP44, single or multisig
:type scheme: str
:param parent_id: Parent Wallet ID used for multisig wallet structures
:type parent_id: int
:param sort_keys: Sort keys according to BIP45 standard (used for multisig keys)
:type sort_keys: bool
:param password: Password to protect passphrase, only used if a passphrase is supplied in the 'key' argument.
:type password: str
:param databasefile: Location of database file. Leave empty to use default
:type databasefile: str
:return HDWallet:
"""
if databasefile is None:
databasefile = DEFAULT_DATABASE
session = DbInit(databasefile=databasefile).session
if session.query(DbWallet).filter_by(name=name).count():
raise WalletError("Wallet with name '%s' already exists" % name)
else:
_logger.info("Create new wallet '%s'" % name)
if name.isdigit():
raise WalletError("Wallet name '%s' invalid, please include letter characters" % name)
if isinstance(key, HDKey):
network = key.network.network_name
elif key:
# If key consists of several words assume it is a passphrase and convert it to a HDKey object
if len(key.split(" ")) > 1:
if not network:
raise WalletError("Please specify network when using passphrase to create a key")
key = HDKey().from_seed(Mnemonic().to_seed(key, password), network=network)
else:
network = check_network_and_key(key, network)
key = HDKey(key, network=network)
elif network is None:
network = DEFAULT_NETWORK
if not name:
raise WalletError("Please enter wallet name")
new_wallet = DbWallet(name=name, owner=owner, network_name=network, purpose=purpose, scheme=scheme,
sort_keys=sort_keys, parent_id=parent_id)
session.add(new_wallet)
session.commit()
new_wallet_id = new_wallet.id
if scheme == 'bip44':
mk = HDWalletKey.from_key(key=key, name=name, session=session, wallet_id=new_wallet_id, network=network,
account_id=account_id, purpose=purpose, key_type='bip32')
if mk.depth > 4:
raise WalletError("Cannot create new wallet with main key of depth 5 or more")
new_wallet.main_key_id = mk.key_id
session.commit()
w = cls(new_wallet_id, databasefile=databasefile, main_key_object=mk.key())
if mk.depth == 0:
nw = Network(network)
networkcode = nw.bip44_cointype
path = ["%d'" % purpose, "%s'" % networkcode]
w._create_keys_from_path(mk, path, name=name, wallet_id=new_wallet_id, network=network, session=session,
account_id=account_id, purpose=purpose, basepath="m")
w.new_account(account_id=account_id)
elif scheme == 'multisig':
w = cls(new_wallet_id, databasefile=databasefile)
elif scheme == 'single':
mk = HDWalletKey.from_key(key=key, name=name, session=session, wallet_id=new_wallet_id, network=network,
account_id=account_id, purpose=purpose, key_type='single')
new_wallet.main_key_id = mk.key_id
session.commit()
w = cls(new_wallet_id, databasefile=databasefile, main_key_object=mk.key())
else:
raise WalletError("Wallet with scheme %s not supported at the moment" % scheme)
session.close()
return w
@classmethod
def create_multisig(cls, name, key_list, sigs_required=None, owner='', network=None, account_id=0, purpose=45,
multisig_compressed=True, sort_keys=True, databasefile=None):
"""
Create a multisig wallet with specified name and list of keys. The list of keys can contain 2 or more
public or private keys. For every key a cosigner wallet will be created with a BIP44 key structure or a
single key depending on the key_type.
:param name: Unique name of this Wallet
:type name: str
:param key_list: List of keys in HDKey format or any other format supported by HDKey class
:type key_list: list
:param sigs_required: Number of signatures required for validation. For example 2 for 2-of-3 multisignature. Default is all keys must signed
:type sigs_required: int
:type owner: str
:param network: Network name, use default if not specified
:type network: str
:param account_id: Account ID, default is 0
:type account_id: int
:param purpose: BIP44 purpose field, default is 44
:type purpose: int
:param multisig_compressed: Use compressed multisig keys for this wallet. Default is True
:type multisig_compressed: bool
:param sort_keys: Sort keys according to BIP45 standard (used for multisig keys)
:type sort_keys: bool
:param databasefile: Location of database file. Leave empty to use default
:type databasefile: str
:return HDWallet:
"""
if databasefile is None:
databasefile = DEFAULT_DATABASE
session = DbInit(databasefile=databasefile).session
if session.query(DbWallet).filter_by(name=name).count():
raise WalletError("Wallet with name '%s' already exists" % name)
else:
_logger.info("Create new multisig wallet '%s'" % name)
if not isinstance(key_list, list):
raise WalletError("Need list of keys to create multi-signature key structure")
if len(key_list) < 2:
raise WalletError("Key list must contain at least 2 keys")
if sigs_required is None:
sigs_required = len(key_list)
if sigs_required > len(key_list):
raise WalletError("Number of keys required to sign is greater then number of keys provided")
hdpm = cls.create(name=name, owner=owner, network=network, account_id=account_id,
purpose=purpose, scheme='multisig', sort_keys=sort_keys, databasefile=databasefile)
hdpm.multisig_compressed = multisig_compressed
co_id = 0
hdpm.cosigner = []
hdkey_list = []
for cokey in key_list:
if not isinstance(cokey, HDKey):
if len(cokey.split(' ')) > 5:
k = HDKey().from_passphrase(cokey, network=network)
else:
k = HDKey(cokey)
hdkey_list.append(k)
else:
hdkey_list.append(cokey)
if sort_keys:
hdkey_list.sort(key=lambda x: x.public_byte)
for cokey in hdkey_list:
if hdpm.network.network_name != cokey.network.network_name:
raise WalletError("Network for key %s (%s) is different then network specified: %s/%s" %
(cokey.wif(), cokey.network.network_name, network, hdpm.network.network_name))
scheme = 'bip44'
wn = name + '-cosigner-%d' % co_id
if cokey.key_type == 'single':
scheme = 'single'
w = cls.create(name=wn, key=cokey, owner=owner, network=network, account_id=account_id,
purpose=purpose, parent_id=hdpm.wallet_id, databasefile=databasefile, scheme=scheme)
hdpm.cosigner.append(w)
co_id += 1
hdpm.multisig_n_required = sigs_required
hdpm.sort_keys = sort_keys
session.query(DbWallet).filter(DbWallet.id == hdpm.wallet_id).\
update({DbWallet.multisig_n_required: sigs_required})
session.commit()
session.close()
return hdpm
def _create_keys_from_path(self, parent, path, wallet_id, account_id, network, session,
name='', basepath='', change=0, purpose=44):
"""
Create all keys for a given path.
:param parent: Main parent key. Can be a BIP0044 master key, level 3 account key, or any other.
:type parent: HDWalletKey
:param path: Path of keys to generate, relative to given parent key
:type path: list
:param wallet_id: Wallet ID
:type wallet_id: int
:param account_id: Account ID
:type account_id: int
:param network: Network
:type network: str
:param session: Sqlalchemy session
:type session: sqlalchemy.orm.session.Session
:param name: Name for generated keys. Leave empty for default
:type name: str
:param basepath: Basepath of main parent key
:type basepath: str
:param change: Change = 1, or payment = 0. Default is 0.
:type change: int
:param purpose: Purpose field according to BIP32 definition, default is 44 for BIP44.
:type purpose: int
:return HDWalletKey:
"""
# Initial checks and settings
if not isinstance(parent, HDWalletKey):
raise WalletError("Parent must be of type 'HDWalletKey'")
if not isinstance(path, list):
raise WalletError("Path must be of type 'list'")
if len(basepath) and basepath[-1] != "/":
basepath += "/"
nk = parent
ck = nk.key()
# Check for closest ancestor in wallet
spath = basepath + '/'.join(path)
rkey = None
while spath and not rkey:
rkey = self._session.query(DbKey).filter_by(wallet_id=wallet_id, path=spath).first()
spath = '/'.join(spath.split("/")[:-1])
if rkey is not None and rkey.path not in [basepath, basepath[:-1]]:
path = (basepath + '/'.join(path)).replace(rkey.path + '/', '').split('/')
basepath = rkey.path + '/'
nk = self.key(rkey.id)
ck = nk.key()
parent_id = nk.key_id
# Create new keys from path
for l in range(len(path)):
pp = "/".join(path[:l+1])
fullpath = basepath + pp
ck = ck.subkey_for_path(path[l], network=network)
nk = HDWalletKey.from_key(key=ck, name=name, wallet_id=wallet_id, network=network,
account_id=account_id, change=change, purpose=purpose, path=fullpath,
parent_id=parent_id, session=session)
self._key_objects.update({nk.key_id: nk})
parent_id = nk.key_id
_logger.info("New key(s) created for parent_id %d" % parent_id)
return nk
def __enter__(self):
return self
def __init__(self, wallet, databasefile=DEFAULT_DATABASE, session=None, main_key_object=None):
"""
Open a wallet with given ID or name
:param wallet: Wallet name or ID