-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathsend.rs
325 lines (285 loc) Β· 8.29 KB
/
send.rs
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
use {
super::*,
crate::{outgoing::Outgoing, wallet::transaction_builder::Target},
base64::Engine,
bitcoin::psbt::Psbt,
};
#[derive(Debug, Parser)]
pub(crate) struct Send {
#[arg(long, help = "Don't sign or broadcast transaction")]
pub(crate) dry_run: bool,
#[arg(long, help = "Use fee rate of <FEE_RATE> sats/vB")]
fee_rate: FeeRate,
#[arg(
long,
help = "Target amount of postage to include with sent inscriptions [default: 10000 sat]"
)]
pub(crate) postage: Option<Amount>,
address: Address<NetworkUnchecked>,
outgoing: Outgoing,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Output {
pub txid: Txid,
pub psbt: String,
pub outgoing: Outgoing,
pub fee: u64,
}
impl Send {
pub(crate) fn run(self, wallet: Wallet) -> SubcommandResult {
let address = self
.address
.clone()
.require_network(wallet.chain().network())?;
let unsigned_transaction = match self.outgoing {
Outgoing::Amount(amount) => {
Self::create_unsigned_send_amount_transaction(&wallet, address, amount, self.fee_rate)?
}
Outgoing::Rune { decimal, rune } => Self::create_unsigned_send_runes_transaction(
&wallet,
address,
rune,
decimal,
self.fee_rate,
)?,
Outgoing::InscriptionId(id) => Self::create_unsigned_send_satpoint_transaction(
&wallet,
address,
wallet.get_inscription_satpoint(id)?,
self.postage,
self.fee_rate,
true,
)?,
Outgoing::SatPoint(satpoint) => Self::create_unsigned_send_satpoint_transaction(
&wallet,
address,
satpoint,
self.postage,
self.fee_rate,
false,
)?,
};
let bitcoin_client = wallet.bitcoin_client()?;
let unspent_outputs = wallet.get_unspent_outputs()?;
let txid = if self.dry_run {
unsigned_transaction.txid()
} else {
let signed_tx = bitcoin_client
.sign_raw_transaction_with_wallet(&unsigned_transaction.clone(), None, None)?
.hex;
bitcoin_client.send_raw_transaction(&signed_tx)?
};
let psbt = bitcoin_client
.wallet_process_psbt(
&base64::engine::general_purpose::STANDARD
.encode(Psbt::from_unsigned_tx(unsigned_transaction.clone())?.serialize()),
Some(false),
None,
None,
)?
.psbt;
Ok(Some(Box::new(Output {
txid,
psbt,
outgoing: self.outgoing,
fee: unsigned_transaction
.input
.iter()
.map(|txin| unspent_outputs.get(&txin.previous_output).unwrap().to_sat())
.sum::<u64>()
.checked_sub(
unsigned_transaction
.output
.iter()
.map(|txout| txout.value)
.sum::<u64>(),
)
.unwrap(),
})))
}
fn lock_non_cardinal_outputs(
bitcoin_client: &Client,
inscriptions: &BTreeMap<SatPoint, Vec<InscriptionId>>,
runic_outputs: &BTreeSet<OutPoint>,
unspent_outputs: &BTreeMap<OutPoint, bitcoin::Amount>,
) -> Result {
let all_inscription_outputs = inscriptions
.keys()
.map(|satpoint| satpoint.outpoint)
.collect::<HashSet<OutPoint>>();
let locked_outputs = unspent_outputs
.keys()
.filter(|utxo| all_inscription_outputs.contains(utxo))
.chain(runic_outputs.iter())
.cloned()
.collect::<Vec<OutPoint>>();
if !bitcoin_client.lock_unspent(&locked_outputs)? {
bail!("failed to lock UTXOs");
}
Ok(())
}
fn create_unsigned_send_amount_transaction(
wallet: &Wallet,
destination: Address,
amount: Amount,
fee_rate: FeeRate,
) -> Result<Transaction> {
let client = wallet.bitcoin_client()?;
let unspent_outputs = wallet.get_unspent_outputs()?;
let inscriptions = wallet.get_inscriptions()?;
let runic_outputs = wallet.get_runic_outputs()?;
Self::lock_non_cardinal_outputs(&client, &inscriptions, &runic_outputs, &unspent_outputs)?;
let unfunded_transaction = Transaction {
version: 2,
lock_time: LockTime::ZERO,
input: Vec::new(),
output: vec![TxOut {
script_pubkey: destination.script_pubkey(),
value: amount.to_sat(),
}],
};
let unsigned_transaction = consensus::encode::deserialize(&fund_raw_transaction(
&client,
fee_rate,
&unfunded_transaction,
)?)?;
Ok(unsigned_transaction)
}
fn create_unsigned_send_satpoint_transaction(
wallet: &Wallet,
destination: Address,
satpoint: SatPoint,
postage: Option<Amount>,
fee_rate: FeeRate,
sending_inscription: bool,
) -> Result<Transaction> {
let unspent_outputs = wallet.get_unspent_outputs()?;
let locked_outputs = wallet.get_locked_outputs()?;
let inscriptions = wallet.get_inscriptions()?;
let runic_outputs = wallet.get_runic_outputs()?;
if !sending_inscription {
for inscription_satpoint in inscriptions.keys() {
if satpoint == *inscription_satpoint {
bail!("inscriptions must be sent by inscription ID");
}
}
}
ensure!(
!runic_outputs.contains(&satpoint.outpoint),
"runic outpoints may not be sent by satpoint"
);
let change = [wallet.get_change_address()?, wallet.get_change_address()?];
let postage = if let Some(postage) = postage {
Target::ExactPostage(postage)
} else {
Target::Postage
};
Ok(
TransactionBuilder::new(
satpoint,
inscriptions,
unspent_outputs.clone(),
locked_outputs,
runic_outputs,
destination.clone(),
change,
fee_rate,
postage,
)
.build_transaction()?,
)
}
fn create_unsigned_send_runes_transaction(
wallet: &Wallet,
destination: Address,
spaced_rune: SpacedRune,
decimal: Decimal,
fee_rate: FeeRate,
) -> Result<Transaction> {
ensure!(
wallet.has_rune_index()?,
"sending runes with `ord send` requires index created with `--index-runes` flag",
);
let unspent_outputs = wallet.get_unspent_outputs()?;
let inscriptions = wallet.get_inscriptions()?;
let runic_outputs = wallet.get_runic_outputs()?;
let bitcoin_client = wallet.bitcoin_client()?;
Self::lock_non_cardinal_outputs(
&bitcoin_client,
&inscriptions,
&runic_outputs,
&unspent_outputs,
)?;
let (id, entry, _parent) = wallet
.get_rune(spaced_rune.rune)?
.with_context(|| format!("rune `{}` has not been etched", spaced_rune.rune))?;
let amount = decimal.to_amount(entry.divisibility)?;
let inscribed_outputs = inscriptions
.keys()
.map(|satpoint| satpoint.outpoint)
.collect::<HashSet<OutPoint>>();
let mut input_runes = 0;
let mut input = Vec::new();
for output in runic_outputs {
if inscribed_outputs.contains(&output) {
continue;
}
let balance = wallet.get_rune_balance_in_output(&output, entry.rune)?;
if balance > 0 {
input_runes += balance;
input.push(output);
}
if input_runes >= amount {
break;
}
}
ensure! {
input_runes >= amount,
"insufficient `{}` balance, only {} in wallet",
spaced_rune,
Pile {
amount: input_runes,
divisibility: entry.divisibility,
symbol: entry.symbol
},
}
let runestone = Runestone {
edicts: vec![Edict {
amount,
id: id.into(),
output: 2,
}],
..Default::default()
};
let unfunded_transaction = Transaction {
version: 2,
lock_time: LockTime::ZERO,
input: input
.into_iter()
.map(|previous_output| TxIn {
previous_output,
script_sig: ScriptBuf::new(),
sequence: Sequence::MAX,
witness: Witness::new(),
})
.collect(),
output: vec![
TxOut {
script_pubkey: runestone.encipher(),
value: 0,
},
TxOut {
script_pubkey: wallet.get_change_address()?.script_pubkey(),
value: TARGET_POSTAGE.to_sat(),
},
TxOut {
script_pubkey: destination.script_pubkey(),
value: TARGET_POSTAGE.to_sat(),
},
],
};
let unsigned_transaction =
fund_raw_transaction(&bitcoin_client, fee_rate, &unfunded_transaction)?;
Ok(consensus::encode::deserialize(&unsigned_transaction)?)
}
}