Repository navigation
Expand file tree
/
Copy pathdesktop_wallet.py
More file actions
277 lines (230 loc) · 11.3 KB
/
Copy pathdesktop_wallet.py
File metadata and controls
277 lines (230 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Dingocoin wallet services for the Windows desktop application."""
from dingo_i18n import tr
from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation
import json
from electrum import bitcoin
from electrum.bip32 import BIP32Node
from electrum.crypto import hash_160
from electrum.descriptor import get_singlesig_descriptor_from_legacy_leaf
from electrum.keystore import bip39_is_checksum_valid, bip39_to_seed
from electrum.storage import WalletStorage
from electrum.stored_dict import StorageEncryptionVersion
from electrum.transaction import PartialTransaction, PartialTxInput, PartialTxOutput, Transaction, TxOutpoint
import mainnet_electrum
from dingo_wallet import COIN, NETWORKS
from wallet_keys import KeySet
DUST = COIN // 100
def coins(value):
return format(Decimal(value) / COIN, ".8f").rstrip("0").rstrip(".") or "0"
def parse_amount(text):
try:
amount = Decimal(text.strip().replace(",", "."))
if not amount.is_finite() or not Decimal("0.01") <= amount < Decimal("10000000000.00000001"):
raise ValueError
base = amount * COIN
if base != base.to_integral_value():
raise ValueError
return int(base)
except (InvalidOperation, ValueError):
raise ValueError(tr("Enter at least 0.01 DINGO with up to 8 decimal places.")) from None
def destination_script(address, network="mainnet"):
try:
payload = bitcoin.DecodeBase58Check(address)
if len(payload) == 21 and network == "mainnet" and payload[0] == 22:
return b"\xa9\x14" + payload[1:] + b"\x87"
if len(payload) != 21 or payload[0] != NETWORKS[network][1]:
raise ValueError
except Exception:
raise ValueError(tr("Enter a Dingocoin address for {network}.").format(network=network)) from None
return b"\x76\xa9\x14" + payload[1:] + b"\x88\xac"
def network_genesis(network):
if network == "mainnet":
return mainnet_electrum.GENESIS
return {
"testnet": "9d060aaabcb8ab8e88c4d20be01f36d727ed3eb03d97e50ac585c5d6ec4bc8cb",
"regtest": "3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5",
}[network]
def transport(network, run):
if run is not None:
return run
if network != "mainnet":
raise ValueError(tr("Mainnet is required."))
return mainnet_electrum.connected
def account_from_words(words, network="mainnet"):
words = " ".join(words.lower().split())
if len(words.split()) not in (12, 15, 18, 21, 24) or bip39_is_checksum_valid(words) != (True, True):
raise ValueError(tr("Check the spelling and order of the words in your BIP39 seed phrase."))
root = BIP32Node.from_rootseed(bip39_to_seed(words, passphrase=""), xtype="standard")
return root.subkey_at_private_derivation(f"m/44'/{NETWORKS[network][0]}'/0'")
class Wallet:
def __init__(self, storage, document, network="mainnet"):
if network not in ("mainnet", "testnet", "regtest"):
raise ValueError(tr("Unknown wallet network."))
self.network = network
self.genesis = network_genesis(network)
if document.get("format") != f"electrum-dingo-{network}-1" or document.get("genesis") != self.genesis:
raise ValueError(tr("This wallet file does not belong to {network}.").format(network=network))
self.storage = storage
self.document = document
self.keys = KeySet(document) if network == "mainnet" else None
self.advanced = bool(document.get("kind") or document.get("master"))
if self.advanced:
if self.keys is None:
raise ValueError(tr("Mainnet is required."))
return
self.account = account_from_words(document["words"], network)
self.branches = [self.account.subkey_at_private_derivation([i]).convert_to_public() for i in range(2)]
@classmethod
def create(cls, path, words, password, network="mainnet"):
return cls.create_with_keys(path, {"words": " ".join(words.lower().split())}, password, network)
@classmethod
def create_with_keys(cls, path, keys, password, network="mainnet"):
if not password:
raise ValueError(tr("Enter a password to encrypt the wallet file."))
storage = WalletStorage(str(path))
if storage.file_exists():
raise ValueError(tr("A file with this name already exists."))
doc = {**keys, "format": f"electrum-dingo-{network}-1", "genesis": network_genesis(network)}
wallet = cls(storage, doc, network)
storage.set_password(password, StorageEncryptionVersion.USER_PASSWORD)
wallet.save()
return wallet
@classmethod
def open(cls, path, password, network="mainnet"):
storage = WalletStorage(str(path))
if not storage.file_exists() or not storage.is_encrypted_with_user_pw():
raise ValueError(tr("Select an encrypted Electrum-DINGO wallet file."))
try:
storage.decrypt(password)
except Exception as e:
raise ValueError(tr("Could not open the wallet. Check the password and the file.")) from e
return cls(storage, json.loads(storage.read()), network)
def change_address(self, index):
if self.keys and self.keys.entries:
return self.address(0, 0)
return self.address(1, index)
def save(self):
self.storage.write(json.dumps(self.document))
def frozen_outpoints(self):
return set(self.document.get("frozen_outputs", []))
def spendable_coins(self, snapshot):
frozen = self.frozen_outpoints()
return [coin for coin in snapshot.utxos if coin.outpoint not in frozen]
def check_unfrozen_inputs(self, inputs):
frozen = self.frozen_outpoints()
for txin in inputs:
ref = f"{txin.txid.hex()}:{txin.vout}"
if ref in frozen:
raise ValueError(tr("Frozen") + ": " + ref)
def check_signed_payment(self, payment):
if self.document.get("frozen_outputs"):
self.check_unfrozen_inputs(payment_inputs(payment))
def set_coin_frozen(self, ref, freeze):
frozen = self.frozen_outpoints()
if (ref in frozen) == freeze:
return
if freeze:
pending = self.document.get("pending")
if pending and any(ref == f"{i.txid.hex()}:{i.vout}" for i in payment_inputs(pending)):
raise ValueError(tr("Complete the previous payment first."))
frozen.add(ref)
else:
frozen.remove(ref)
updated = sorted(frozen)
self.storage.write(json.dumps({**self.document, "frozen_outputs": updated}))
self.document["frozen_outputs"] = updated
def address(self, branch, index):
if self.advanced:
return self.keys.address(branch,index)
key = self.branches[branch].subkey_at_public_derivation([index]).eckey
return bitcoin.hash160_to_b58_address(hash_160(key.get_public_key_bytes(compressed=True)), NETWORKS[self.network][1])
def payment_inputs(payment):
from embit.transaction import Transaction as RawTransaction
return RawTransaction.from_string(payment["hex"]).vin
@dataclass(frozen=True)
class Coin:
txid: str
index: int
value: int
branch: int
child: int
@property
def outpoint(self):
return f"{self.txid}:{self.index}"
@dataclass
class Snapshot:
confirmed: int
pending: int
utxos: list
next_indices: list
addresses: list = field(default_factory=list)
transactions: list = field(default_factory=list)
def discover(wallet, *, history=False, run=None):
return transport(wallet.network, run)(lambda client: mainnet_electrum.scan(client, wallet, history))
def estimated_fee(input_count, rate, input_size=149):
# Dingocoin Core CFeeRate::GetFee charges each started 1000-byte unit.
size = 10 + input_size * input_count + 68
return ((size + 999) // 1000) * rate
def prepare(wallet, snapshot, destination, amount, fee_rate=COIN, *, run=None):
script = destination_script(destination, wallet.network)
if amount < DUST:
raise ValueError(tr("The minimum amount is 0.01 DINGO."))
selected = []
total = 0
for coin in sorted(wallet.spendable_coins(snapshot), key=lambda u: u.value, reverse=True):
selected.append(coin)
total += coin.value
# Core's recommended 1 DINGO/kB, using a conservative P2PKH size.
fee = estimated_fee(len(selected), fee_rate, wallet.keys.input_bytes() if wallet.keys else 149)
if total >= amount + fee:
break
else:
raise ValueError(tr("Insufficient confirmed DINGO to cover the amount and fee."))
inputs, keypairs = [], {}
parents = []
for coin in selected:
raw = mainnet_electrum.raw_transaction(coin.txid, transport(wallet.network, run))
parent = Transaction(raw)
if parent.txid() != coin.txid or not 0 <= coin.index < len(parent.outputs()):
raise ValueError(tr("The previous transaction failed verification."))
output = parent.outputs()[coin.index]
expected = destination_script(wallet.address(coin.branch, coin.child), wallet.network)
if output.value != coin.value or output.scriptpubkey != expected:
raise ValueError(tr("The input amount or owner does not match."))
if wallet.advanced:
from embit.transaction import Transaction as LegacyTransaction
parents.append(LegacyTransaction.from_string(raw))
continue
key = wallet.account.subkey_at_private_derivation([coin.branch, coin.child]).eckey
pub = key.get_public_key_bytes(compressed=True)
txin = PartialTxInput(prevout=TxOutpoint(bytes.fromhex(coin.txid), coin.index), nsequence=0xffffffff)
txin.utxo = parent
txin.script_descriptor = get_singlesig_descriptor_from_legacy_leaf(pubkey=pub.hex(), script_type="p2pkh")
inputs.append(txin)
keypairs[pub] = key.get_secret_bytes()
change = total - amount - fee
if wallet.advanced:
from dingo_psbt import proposal
return proposal(wallet, selected, parents, destination, amount,
change if change >= DUST else 0, snapshot.next_indices[1])
outputs = [PartialTxOutput(scriptpubkey=script, value=amount)]
if change >= DUST:
change_addr = wallet.address(1, snapshot.next_indices[1])
outputs.append(PartialTxOutput(scriptpubkey=destination_script(change_addr, wallet.network), value=change))
else:
fee += change
tx = PartialTransaction.from_io(inputs, outputs, version=1, locktime=0, BIP69_sort=False)
tx.sign(keypairs)
if not tx.is_complete():
raise ValueError(tr("Could not sign all inputs."))
raw = tx.serialize_to_network()
return {"network": wallet.network, "txid": Transaction(raw).txid(), "hex": raw, "address": destination, "amount": amount, "fee": fee}
def seen(payment, *, run=None):
return transport(payment["network"], run)(lambda c: mainnet_electrum.is_seen(c, payment))
def broadcast(payment, network="mainnet", *, run=None):
if network != payment.get("network"):
raise ValueError(tr("The payment and wallet networks do not match."))
if Transaction(payment["hex"]).txid() != payment["txid"]:
raise ValueError(tr("The TXID does not match the signed transaction."))
return transport(network, run)(lambda c: mainnet_electrum.broadcast(c, payment))