-
Notifications
You must be signed in to change notification settings - Fork 221
/
pool.rs
469 lines (424 loc) · 16.3 KB
/
pool.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
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
use crate::error::RPCError;
use ckb_chain_spec::consensus::Consensus;
use ckb_fee_estimator::FeeRate;
use ckb_jsonrpc_types::{OutputsValidator, Transaction, TxPoolInfo};
use ckb_logger::error;
use ckb_network::PeerIndex;
use ckb_script::IllTransactionChecker;
use ckb_shared::shared::Shared;
use ckb_sync::SyncShared;
use ckb_tx_pool::error::Reject;
use ckb_types::{core, packed, prelude::*, H256};
use ckb_verification::{Since, SinceMetric};
use jsonrpc_core::Result;
use jsonrpc_derive::rpc;
use std::convert::TryInto;
use std::sync::Arc;
#[rpc(server)]
pub trait PoolRpc {
// curl -d '{"id": 2, "jsonrpc": "2.0", "method":"send_transaction","params": [{"version":2, "deps":[], "inputs":[], "outputs":[]}]}' -H 'content-type:application/json' 'http://localhost:8114'
#[rpc(name = "send_transaction")]
fn send_transaction(
&self,
_tx: Transaction,
_outputs_validator: Option<OutputsValidator>,
) -> Result<H256>;
// curl -d '{"params": [], "method": "tx_pool_info", "jsonrpc": "2.0", "id": 2}' -H 'content-type:application/json' http://localhost:8114
#[rpc(name = "tx_pool_info")]
fn tx_pool_info(&self) -> Result<TxPoolInfo>;
// curl -d '{"params": [], "method": "clear_tx_pool", "jsonrpc": "2.0", "id": 2}' -H 'content-type:application/json' http://localhost:8114
#[rpc(name = "clear_tx_pool")]
fn clear_tx_pool(&self) -> Result<()>;
}
pub(crate) struct PoolRpcImpl {
sync_shared: Arc<SyncShared>,
shared: Shared,
min_fee_rate: FeeRate,
reject_ill_transactions: bool,
}
impl PoolRpcImpl {
pub fn new(
shared: Shared,
sync_shared: Arc<SyncShared>,
min_fee_rate: FeeRate,
reject_ill_transactions: bool,
) -> PoolRpcImpl {
PoolRpcImpl {
sync_shared,
shared,
min_fee_rate,
reject_ill_transactions,
}
}
}
impl PoolRpc for PoolRpcImpl {
fn send_transaction(
&self,
tx: Transaction,
outputs_validator: Option<OutputsValidator>,
) -> Result<H256> {
let tx: packed::Transaction = tx.into();
let tx: core::TransactionView = tx.into_view();
if let Err(e) = match outputs_validator {
Some(OutputsValidator::Default) => {
DefaultOutputsValidator::new(self.shared.consensus()).validate(&tx)
}
Some(OutputsValidator::Passthrough) | None => Ok(()),
} {
return Err(RPCError::custom_with_data(
RPCError::PoolRejectedTransactionByOutputsValidator,
format!(
"The transction is rejected by OutputsValidator set in params[1]: {}. \
Please set it to passthrough if you really want to send transactions with advanced scripts.",
outputs_validator.unwrap_or(OutputsValidator::Default).json_display()
),
e,
));
}
if self.reject_ill_transactions {
if let Err(e) = IllTransactionChecker::new(&tx).check() {
return Err(RPCError::custom_with_data(
RPCError::PoolRejectedTransactionByIllTransactionChecker,
"The transaction is rejected by IllTransactionChecker",
e,
));
}
}
let tx_pool = self.shared.tx_pool_controller();
let submit_txs = tx_pool.submit_txs(vec![tx.clone()]);
if let Err(e) = submit_txs {
error!("send submit_txs request error {}", e);
return Err(RPCError::ckb_internal_error(e));
}
let broadcast = |tx_hash: packed::Byte32| {
// workaround: we are using `PeerIndex(usize::max)` to indicate that tx hash source is itself.
let peer_index = PeerIndex::new(usize::max_value());
self.sync_shared
.state()
.tx_hashes()
.entry(peer_index)
.or_default()
.insert(tx_hash);
};
let tx_hash = tx.hash();
match submit_txs.unwrap() {
Ok(_) => {
broadcast(tx_hash.clone());
Ok(tx_hash.unpack())
}
Err(e) => match RPCError::downcast_submit_transaction_reject(&e) {
Some(reject) => {
if let Reject::Duplicated(_) = reject {
broadcast(tx_hash);
}
Err(RPCError::from_submit_transaction_reject(reject))
}
None => Err(RPCError::ckb_internal_error(e)),
},
}
}
fn tx_pool_info(&self) -> Result<TxPoolInfo> {
let tx_pool = self.shared.tx_pool_controller();
let get_tx_pool_info = tx_pool.get_tx_pool_info();
if let Err(e) = get_tx_pool_info {
error!("send get_tx_pool_info request error {}", e);
return Err(RPCError::ckb_internal_error(e));
};
let tx_pool_info = get_tx_pool_info.unwrap();
Ok(TxPoolInfo {
tip_hash: tx_pool_info.tip_hash.unpack(),
tip_number: tx_pool_info.tip_number.into(),
pending: (tx_pool_info.pending_size as u64).into(),
proposed: (tx_pool_info.proposed_size as u64).into(),
orphan: (tx_pool_info.orphan_size as u64).into(),
total_tx_size: (tx_pool_info.total_tx_size as u64).into(),
total_tx_cycles: tx_pool_info.total_tx_cycles.into(),
min_fee_rate: self.min_fee_rate.as_u64().into(),
last_txs_updated_at: tx_pool_info.last_txs_updated_at.into(),
})
}
fn clear_tx_pool(&self) -> Result<()> {
let snapshot = Arc::clone(&self.shared.snapshot());
let tx_pool = self.shared.tx_pool_controller();
tx_pool
.clear_pool(snapshot)
.map_err(|err| RPCError::custom(RPCError::Invalid, err.to_string()))?;
Ok(())
}
}
struct DefaultOutputsValidator<'a> {
consensus: &'a Consensus,
}
#[derive(Debug)]
enum DefaultOutputsValidatorError {
HashType,
CodeHash,
ArgsLen,
ArgsSince,
}
impl<'a> DefaultOutputsValidator<'a> {
pub fn new(consensus: &'a Consensus) -> Self {
Self { consensus }
}
pub fn validate(&self, tx: &core::TransactionView) -> std::result::Result<(), String> {
tx.outputs()
.into_iter()
.enumerate()
.try_for_each(|(index, output)| {
self.validate_lock_script(&output)
.and(self.validate_type_script(&output))
.map_err(|err| format!("output index: {}, error: {:?}", index, err))
})
}
fn validate_lock_script(
&self,
output: &packed::CellOutput,
) -> std::result::Result<(), DefaultOutputsValidatorError> {
self.validate_secp256k1_blake160_sighash_all(output)
.or_else(|_| self.validate_secp256k1_blake160_multisig_all(output))
}
fn validate_type_script(
&self,
output: &packed::CellOutput,
) -> std::result::Result<(), DefaultOutputsValidatorError> {
self.validate_dao(output)
}
fn validate_secp256k1_blake160_sighash_all(
&self,
output: &packed::CellOutput,
) -> std::result::Result<(), DefaultOutputsValidatorError> {
let script = output.lock();
if !script.is_hash_type_type() {
Err(DefaultOutputsValidatorError::HashType)
} else if script.code_hash()
!= self
.consensus
.secp256k1_blake160_sighash_all_type_hash()
.expect("No secp256k1_blake160_sighash_all system cell")
{
Err(DefaultOutputsValidatorError::CodeHash)
} else if script.args().len() != BLAKE160_LEN {
Err(DefaultOutputsValidatorError::ArgsLen)
} else {
Ok(())
}
}
fn validate_secp256k1_blake160_multisig_all(
&self,
output: &packed::CellOutput,
) -> std::result::Result<(), DefaultOutputsValidatorError> {
let script = output.lock();
if !script.is_hash_type_type() {
Err(DefaultOutputsValidatorError::HashType)
} else if script.code_hash()
!= self
.consensus
.secp256k1_blake160_multisig_all_type_hash()
.expect("No secp256k1_blake160_multisig_all system cell")
{
Err(DefaultOutputsValidatorError::CodeHash)
} else if script.args().len() != BLAKE160_LEN {
if script.args().len() == BLAKE160_LEN + SINCE_LEN {
if extract_since_from_secp256k1_blake160_multisig_all_args(&script).flags_is_valid()
{
Ok(())
} else {
Err(DefaultOutputsValidatorError::ArgsSince)
}
} else {
Err(DefaultOutputsValidatorError::ArgsLen)
}
} else {
Ok(())
}
}
fn validate_dao(
&self,
output: &packed::CellOutput,
) -> std::result::Result<(), DefaultOutputsValidatorError> {
match output.type_().to_opt() {
Some(script) => {
if !script.is_hash_type_type() {
Err(DefaultOutputsValidatorError::HashType)
} else if script.code_hash()
!= self.consensus.dao_type_hash().expect("No dao system cell")
{
Err(DefaultOutputsValidatorError::CodeHash)
} else if output.lock().args().len() == BLAKE160_LEN + SINCE_LEN {
// https://github.com/nervosnetwork/ckb/wiki/Common-Gotchas#nervos-dao
let since =
extract_since_from_secp256k1_blake160_multisig_all_args(&output.lock());
match since.extract_metric() {
Some(SinceMetric::EpochNumberWithFraction(_)) if since.is_absolute() => {
Ok(())
}
_ => Err(DefaultOutputsValidatorError::ArgsSince),
}
} else {
Ok(())
}
}
None => Ok(()),
}
}
}
const BLAKE160_LEN: usize = 20;
const SINCE_LEN: usize = 8;
fn extract_since_from_secp256k1_blake160_multisig_all_args(script: &packed::Script) -> Since {
Since(u64::from_le_bytes(
(&script.args().raw_data()[BLAKE160_LEN..])
.try_into()
.expect("checked len"),
))
}
#[cfg(test)]
mod tests {
use super::*;
use ckb_test_chain_utils::ckb_testnet_consensus;
use ckb_types::{core, packed};
#[test]
fn test_default_outputs_validator() {
let consensus = ckb_testnet_consensus();
let validator = DefaultOutputsValidator::new(&consensus);
{
let type_hash = consensus
.secp256k1_blake160_sighash_all_type_hash()
.unwrap();
// valid output lock
let tx = build_tx(&type_hash, core::ScriptHashType::Type, vec![1; 20]);
assert!(validator.validate(&tx).is_ok());
// invalid args len
let tx = build_tx(&type_hash, core::ScriptHashType::Type, vec![1; 19]);
assert!(validator.validate(&tx).is_err());
// invalid hash type
let tx = build_tx(&type_hash, core::ScriptHashType::Data, vec![1; 20]);
assert!(validator.validate(&tx).is_err());
// invalid code hash
let tx = build_tx(
&consensus.dao_type_hash().unwrap(),
core::ScriptHashType::Type,
vec![1; 20],
);
assert!(validator.validate(&tx).is_err());
}
{
let type_hash = consensus
.secp256k1_blake160_multisig_all_type_hash()
.unwrap();
// valid output lock
let tx = build_tx(&type_hash, core::ScriptHashType::Type, vec![1; 20]);
assert!(validator.validate(&tx).is_ok());
// valid output lock
let since: u64 = (0b1100_0000 << 56) | 42; // relative timestamp 42 seconds
let mut args = vec![1; 20];
args.extend_from_slice(&since.to_le_bytes());
let tx = build_tx(&type_hash, core::ScriptHashType::Type, args);
assert!(validator.validate(&tx).is_ok());
// invalid args len
let tx = build_tx(&type_hash, core::ScriptHashType::Type, vec![1; 19]);
assert!(validator.validate(&tx).is_err());
// invalid hash type
let tx = build_tx(&type_hash, core::ScriptHashType::Data, vec![1; 20]);
assert!(validator.validate(&tx).is_err());
// invalid since args format
let tx = build_tx(&type_hash, core::ScriptHashType::Type, vec![1; 28]);
assert!(validator.validate(&tx).is_err());
}
{
let lock_type_hash = consensus
.secp256k1_blake160_multisig_all_type_hash()
.unwrap();
let type_type_hash = consensus.dao_type_hash().unwrap();
// valid output lock
let tx = build_tx_with_type(
&lock_type_hash,
core::ScriptHashType::Type,
vec![1; 20],
&type_type_hash,
core::ScriptHashType::Type,
);
assert!(validator.validate(&tx).is_ok());
// valid output lock
let since: u64 = (0b0010_0000 << 56) | 42; // absolute epoch
let mut args = vec![1; 20];
args.extend_from_slice(&since.to_le_bytes());
let tx = build_tx_with_type(
&lock_type_hash,
core::ScriptHashType::Type,
args,
&type_type_hash,
core::ScriptHashType::Type,
);
assert!(validator.validate(&tx).is_ok());
// invalid since arg lock
let since: u64 = (0b1100_0000 << 56) | 42; // relative timestamp 42 seconds
let mut args = vec![1; 20];
args.extend_from_slice(&since.to_le_bytes());
let tx = build_tx_with_type(
&lock_type_hash,
core::ScriptHashType::Type,
args,
&type_type_hash,
core::ScriptHashType::Type,
);
assert!(validator.validate(&tx).is_err());
// invalid since args type
let tx = build_tx_with_type(
&lock_type_hash,
core::ScriptHashType::Type,
vec![1; 20],
&type_type_hash,
core::ScriptHashType::Data,
);
assert!(validator.validate(&tx).is_err());
// invalid code hash
let tx = build_tx_with_type(
&lock_type_hash,
core::ScriptHashType::Type,
vec![1; 20],
&lock_type_hash,
core::ScriptHashType::Type,
);
assert!(validator.validate(&tx).is_err());
}
}
fn build_tx(
code_hash: &packed::Byte32,
hash_type: core::ScriptHashType,
args: Vec<u8>,
) -> core::TransactionView {
let lock = packed::ScriptBuilder::default()
.code_hash(code_hash.clone())
.hash_type(hash_type.into())
.args(args.pack())
.build();
core::TransactionBuilder::default()
.output(packed::CellOutput::new_builder().lock(lock).build())
.build()
}
fn build_tx_with_type(
lock_code_hash: &packed::Byte32,
lock_hash_type: core::ScriptHashType,
lock_args: Vec<u8>,
type_code_hash: &packed::Byte32,
type_hash_type: core::ScriptHashType,
) -> core::TransactionView {
let lock = packed::ScriptBuilder::default()
.code_hash(lock_code_hash.clone())
.hash_type(lock_hash_type.into())
.args(lock_args.pack())
.build();
let type_ = packed::ScriptBuilder::default()
.code_hash(type_code_hash.clone())
.hash_type(type_hash_type.into())
.build();
core::TransactionBuilder::default()
.output(
packed::CellOutput::new_builder()
.lock(lock)
.type_(Some(type_).pack())
.build(),
)
.build()
}
}