forked from spesmilo/electrum
/
Send.kt
417 lines (365 loc) · 14.6 KB
/
Send.kt
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
package org.electroncash.electroncash3
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.Menu
import android.view.MenuItem
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.chaquo.python.Kwarg
import com.chaquo.python.PyException
import com.chaquo.python.PyObject
import com.google.zxing.integration.android.IntentIntegrator
import kotlinx.android.synthetic.main.send.*
val libPaymentRequest by lazy { libMod("paymentrequest") }
val libStorage by lazy { libMod("storage") }
val MIN_FEE = 1 // sat/byte
class SendDialog : TaskLauncherDialog<Unit>() {
val wallet = daemonModel.wallet!!
class Model : ViewModel() {
var paymentRequest: PyObject? = null
val tx = BackgroundLiveData<TxArgs, TxResult>().apply {
notifyIncomplete = false // Only notify transactions which match the UI state.
function = { it.invoke() }
}
}
val model: Model by viewModels()
// The "unbroadcasted" flag controls whether the dialog opens as "Send" (false) or
// "Save" (true). If the dialog type has been explicitly set via an argument (e.g. from
// Main.kt), use it; otherwise, non-multisig and 1-of-n multisig wallets will open the dialog
// as "Send", and other m-of-n multisig wallets will open it as "Save".
val unbroadcasted by lazy {
if (arguments != null && arguments!!.containsKey("unbroadcasted")) {
arguments!!.getBoolean("unbroadcasted")
} else {
val multisigType = libStorage.callAttr("multisig_type", daemonModel.walletType)
?.toJava(IntArray::class.java)
multisigType != null && multisigType[0] != 1
}
}
lateinit var amountBox: AmountBox
var settingAmount = false // Prevent infinite recursion.
init {
// The SendDialog shouldn't be dismissed until the SendPasswordDialog succeeds.
dismissAfterExecute = false
if (daemonModel.wallet!!.callAttr("is_watching_only").toBoolean()) {
throw ToastException(R.string.this_wallet_is)
} else if (daemonModel.wallet!!.callAttr("get_receiving_addresses")
.asList().isEmpty()) {
// At least one receiving address is needed to call wallet.dummy_address.
throw ToastException(
R.string.electron_cash_is_generating_your_addresses__please_wait_)
}
}
override fun onBuildDialog(builder: AlertDialog.Builder) {
if (!unbroadcasted) {
builder.setTitle(R.string.send)
.setPositiveButton(R.string.send, null)
} else {
builder.setTitle(R.string.save_transaction)
.setPositiveButton(R.string.sign, null)
}
builder.setView(R.layout.send)
.setNegativeButton(android.R.string.cancel, null)
.setNeutralButton(R.string.qr_code, null)
}
override fun onShowDialog() {
etAddress.addAfterTextChangedListener { s: Editable ->
val scheme = libNetworks.get("net")!!.get("CASHADDR_PREFIX")!!.toString()
if (s.startsWith(scheme + ":")) {
onUri(s.toString())
} else {
refreshTx()
}
}
amountBox = AmountBox(dialog)
amountBox.listener = {
if (!settingAmount) {
btnMax.isChecked = false
refreshTx()
}
}
setPaymentRequest(model.paymentRequest)
btnMax.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
setAmount(null)
}
refreshTx()
}
with (sbFee) {
// setMin is not available until API level 26, so values are offset by MIN_FEE.
progress = (daemonModel.config.callAttr("fee_per_kb").toInt() / 1000) - MIN_FEE
max = (daemonModel.config.callAttr("max_fee_rate").toInt() / 1000) - MIN_FEE
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
var tracking = false // Avoid flickering while tracking.
override fun onProgressChanged(seekBar: SeekBar, progress: Int,
fromUser: Boolean) {
settings.getInt("fee_per_kb").setValue(feeSpb * 1000)
setFeeLabel()
if (!tracking) { // Maybe the value can be changed without a touch.
refreshTx()
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
tracking = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
tracking = false
refreshTx()
}
})
}
setFeeLabel()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { onOK() }
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener { scanQR(this) }
model.tx.observe(this, Observer { onTx(it) })
}
override fun onFirstShowDialog() {
if (arguments != null) {
val address = arguments!!.getString("address")
if (address != null) {
etAddress.setText(address)
amountBox.requestFocus()
}
}
refreshTx()
}
val feeSpb: Int
get() = MIN_FEE + sbFee.progress
fun refreshTx() {
model.tx.refresh(TxArgs(wallet, model.paymentRequest, etAddress.text.toString(),
amountBox.amount, btnMax.isChecked))
}
fun onTx(result: TxResult) {
val tx = try {
result.get()
} catch (e: ToastException) {
null // Don't show it until the user clicks Send.
}
if (btnMax.isChecked && tx != null) {
setAmount(tx.callAttr("output_value").toLong())
}
setFeeLabel(tx)
}
fun setAmount(amount: Long?) {
try {
settingAmount = true
amountBox.amount = amount
} finally {
settingAmount = false
}
}
fun setFeeLabel(tx: PyObject? = null) {
var feeLabel = getString(R.string.sat_byte, feeSpb)
if (tx != null) {
val fee = tx.callAttr("get_fee").toLong()
feeLabel += " (${ltr(formatSatoshisAndUnit(fee))})"
}
tvFeeLabel.setText(feeLabel)
}
class TxArgs(val wallet: PyObject, val pr: PyObject?, val addrStr: String,
val amount: Long?, val max: Boolean) {
fun invoke(): TxResult {
var isDummy = false
val outputs: PyObject
if (pr != null) {
outputs = pr.callAttr("get_outputs")
} else {
val addr = try {
makeAddress(addrStr)
} catch (e: ToastException) {
isDummy = true
wallet.callAttr("dummy_address")
}
if (amount == null && !max) {
return TxResult(ToastException(R.string.Invalid_amount))
}
val output = py.builtins.callAttr(
"tuple", arrayOf(libBitcoin.get("TYPE_ADDRESS"), addr,
if (max) "!" else amount))
outputs = py.builtins.callAttr("list", arrayOf(output))
}
val inputs = wallet.callAttr("get_spendable_coins", null, daemonModel.config,
Kwarg("isInvoice", pr != null))
return try {
TxResult(wallet.callAttr("make_unsigned_transaction", inputs, outputs,
daemonModel.config, Kwarg("sign_schnorr", signSchnorr())),
isDummy)
} catch (e: PyException) {
TxResult(if (e.message!!.startsWith("NotEnoughFunds"))
ToastException(R.string.insufficient_funds) else e)
}
}
}
class TxResult(val tx: PyObject?, val isDummy: Boolean, val error: Throwable? = null) {
constructor(error: Throwable) : this(null, false, error)
fun get() = tx ?: throw error!!
}
// Receives the result of a QR scan.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null && result.contents != null) {
onUri(result.contents)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
fun onUri(uri: String) {
try {
val parsed: PyObject
try {
parsed = libWeb.callAttr("parse_URI", uri)!!
} catch (e: PyException) {
throw ToastException(e)
}
val r = parsed.callAttr("get", "r")
if (r != null) {
showDialog(this, GetPaymentRequestDialog(r.toString()))
} else {
setPaymentRequest(null)
parsed.callAttr("get", "address")?.let { etAddress.setText(it.toString()) }
parsed.callAttr("get", "message")?.let { etDescription.setText(it.toString()) }
parsed.callAttr("get", "amount")?.let { amountBox.amount = it.toLong() }
amountBox.requestFocus()
btnMax.isChecked = false
}
} catch (e: ToastException) {
e.show()
}
}
fun setPaymentRequest(pr: PyObject?) {
model.paymentRequest = pr
for (et in listOf(etAddress, etDescription)) {
setEditable(et, (pr == null))
}
amountBox.isEditable = (pr == null)
btnMax.isEnabled = (pr == null)
if (pr != null) {
etAddress.setText(pr.callAttr("get_requestor").toString())
amountBox.amount = pr.callAttr("get_amount").toLong()
btnMax.isChecked = false
etDescription.setText(pr.callAttr("get_memo").toString())
}
btnContacts.setImageResource(if (pr == null) R.drawable.ic_person_24dp
else R.drawable.ic_check_24dp)
btnContacts.setOnClickListener {
if (pr == null) {
showDialog(this, SendContactsDialog())
} else {
toast(pr.callAttr("get_verify_status").toString())
}
}
}
fun onOK() {
if (model.tx.isComplete()) {
onPostExecute(Unit)
} else {
launchTask()
}
}
override fun doInBackground() {
model.tx.waitUntilComplete()
}
override fun onPostExecute(result: Unit) {
try {
val txResult = model.tx.value!!
if (txResult.isDummy) throw ToastException(R.string.Invalid_address)
txResult.get() // May throw other ToastExceptions.
showDialog(this, SendPasswordDialog().apply { arguments = Bundle().apply {
putString("description", this@SendDialog.etDescription.text.toString())
}})
} catch (e: ToastException) { e.show() }
}
}
class GetPaymentRequestDialog() : TaskDialog<PyObject>() {
val sendDialog by lazy { targetFragment as SendDialog }
constructor(url: String) : this() {
arguments = Bundle().apply { putString("url", url) }
}
override fun doInBackground(): PyObject {
val pr = libPaymentRequest.callAttr("get_payment_request",
arguments!!.getString("url")!!)!!
if (!pr.callAttr("verify", sendDialog.wallet.get("contacts")!!).toBoolean()) {
throw ToastException(pr.get("error").toString())
}
checkExpired(pr)
return pr
}
override fun onPostExecute(result: PyObject) {
sendDialog.setPaymentRequest(result)
}
}
class SendContactsDialog : MenuDialog() {
val sendDialog by lazy { targetFragment as SendDialog }
val contacts: List<PyObject> by lazy {
guiContacts.callAttr("get_contacts", sendDialog.wallet).asList()
}
override fun onBuildDialog(builder: AlertDialog.Builder, menu: Menu) {
builder.setTitle(R.string.contacts)
contacts.forEachIndexed { i, contact ->
menu.add(Menu.NONE, i, Menu.NONE, contact.get("name").toString())
}
}
override fun onShowDialog() {
if (contacts.isEmpty()) {
toast(R.string.you_dont_have_any_contacts)
dismiss()
}
}
override fun onMenuItemSelected(item: MenuItem) {
val address = makeAddress(contacts.get(item.itemId).get("address").toString())
with (sendDialog) {
etAddress.setText(address.callAttr("to_ui_string").toString())
amountBox.requestFocus()
}
}
}
class SendPasswordDialog : PasswordDialog<Unit>() {
val sendDialog by lazy { targetFragment as SendDialog }
val tx by lazy { sendDialog.model.tx.value!!.get() }
override fun onPassword(password: String) {
val wallet = sendDialog.wallet
wallet.callAttr("sign_transaction", tx, password)
if (!sendDialog.unbroadcasted) {
if (!daemonModel.isConnected()) {
throw ToastException(R.string.not_connected)
}
val pr = sendDialog.model.paymentRequest
val result = if (pr != null) {
checkExpired(pr)
val refundAddr = wallet.callAttr("get_receiving_addresses").asList().get(0)
pr.callAttr("send_payment", tx.toString(), refundAddr)
} else {
daemonModel.network.callAttr("broadcast_transaction", tx)
}
checkBroadcastResult(result)
setDescription(wallet, tx.callAttr("txid").toString(),
arguments!!.getString("description")!!)
}
}
override fun onPostExecute(result: Unit) {
sendDialog.dismiss()
if (!sendDialog.unbroadcasted) {
toast(R.string.payment_sent, Toast.LENGTH_SHORT)
} else {
copyToClipboard(tx.toString(), R.string.signed_transaction)
}
}
}
private fun checkExpired(pr: PyObject) {
if (pr.callAttr("has_expired").toBoolean()) {
throw ToastException(R.string.payment_request_has)
}
}
fun checkBroadcastResult(result: PyObject) {
val success = result.asList().get(0).toBoolean()
if (!success) {
var message = result.asList().get(1).toString()
message = message.replace(Regex("^error: (.*)"), "$1")
throw ToastException(message)
}
}