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
use std::default::Default;
use std::{error, fmt};
use serde;
use blockdata::opcodes;
use network::encodable::{ConsensusDecodable, ConsensusEncodable};
use network::serialize::{SimpleDecoder, SimpleEncoder};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Script(Box<[u8]>);
impl fmt::Debug for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut index = 0;
try!(f.write_str("Script("));
while index < self.0.len() {
let opcode = opcodes::All::from(self.0[index]);
index += 1;
let data_len = if let opcodes::Class::PushBytes(n) = opcode.classify() {
n as usize
} else {
match opcode {
opcodes::All::OP_PUSHDATA1 => {
if self.0.len() < index + 1 {
try!(f.write_str("<unexpected end>"));
break;
}
match read_uint(&self.0[index..], 1) {
Ok(n) => { index += 1; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; }
}
}
opcodes::All::OP_PUSHDATA2 => {
if self.0.len() < index + 2 {
try!(f.write_str("<unexpected end>"));
break;
}
match read_uint(&self.0[index..], 2) {
Ok(n) => { index += 2; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; }
}
}
opcodes::All::OP_PUSHDATA4 => {
if self.0.len() < index + 4 {
try!(f.write_str("<unexpected end>"));
break;
}
match read_uint(&self.0[index..], 4) {
Ok(n) => { index += 4; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; }
}
}
_ => 0
}
};
if index > 1 { try!(f.write_str(" ")); }
if opcode == opcodes::All::OP_PUSHBYTES_0 {
try!(f.write_str("OP_0"));
} else {
try!(write!(f, "{:?}", opcode));
}
if data_len > 0 {
try!(f.write_str(" "));
if index + data_len <= self.0.len() {
for ch in &self.0[index..index + data_len] {
try!(write!(f, "{:02x}", ch));
}
index += data_len;
} else {
try!(f.write_str("<push past end>"));
break;
}
}
}
f.write_str(")")
}
}
impl fmt::Display for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl fmt::LowerHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() {
try!(write!(f, "{:02x}", ch));
}
Ok(())
}
}
impl fmt::UpperHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() {
try!(write!(f, "{:02X}", ch));
}
Ok(())
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Builder(Vec<u8>);
display_from_debug!(Builder);
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum Error {
EarlyEndOfScript,
NumericOverflow,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))
}
}
impl error::Error for Error {
fn cause(&self) -> Option<&error::Error> { None }
fn description(&self) -> &'static str {
match *self {
Error::EarlyEndOfScript => "unexpected end of script",
Error::NumericOverflow => "numeric overflow (number on stack larger than 4 bytes)",
}
}
}
fn build_scriptint(n: i64) -> Vec<u8> {
if n == 0 { return vec![] }
let neg = n < 0;
let mut abs = if neg { -n } else { n } as usize;
let mut v = vec![];
while abs > 0xFF {
v.push((abs & 0xFF) as u8);
abs >>= 8;
}
if abs & 0x80 != 0 {
v.push(abs as u8);
v.push(if neg { 0x80u8 } else { 0u8 });
}
else {
abs |= if neg { 0x80 } else { 0 };
v.push(abs as u8);
}
v
}
pub fn read_scriptint(v: &[u8]) -> Result<i64, Error> {
let len = v.len();
if len == 0 { return Ok(0); }
if len > 4 { return Err(Error::NumericOverflow); }
let (mut ret, sh) = v.iter()
.fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));
if v[len - 1] & 0x80 != 0 {
ret &= (1 << (sh - 1)) - 1;
ret = -ret;
}
Ok(ret)
}
#[inline]
pub fn read_scriptbool(v: &[u8]) -> bool {
!(v.is_empty() ||
((v[v.len() - 1] == 0 || v[v.len() - 1] == 0x80) &&
v.iter().rev().skip(1).all(|&w| w == 0)))
}
pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
if data.len() < size {
Err(Error::EarlyEndOfScript)
} else {
let mut ret = 0;
for (i, item) in data.iter().take(size).enumerate() {
ret += (*item as usize) << (i * 8);
}
Ok(ret)
}
}
impl Script {
pub fn new() -> Script { Script(vec![].into_boxed_slice()) }
pub fn len(&self) -> usize { self.0.len() }
pub fn is_empty(&self) -> bool { self.0.is_empty() }
pub fn into_vec(self) -> Vec<u8> { self.0.into_vec() }
#[inline]
pub fn is_p2sh(&self) -> bool {
self.0.len() == 23 &&
self.0[0] == opcodes::All::OP_HASH160 as u8 &&
self.0[1] == opcodes::All::OP_PUSHBYTES_20 as u8 &&
self.0[22] == opcodes::All::OP_EQUAL as u8
}
pub fn is_provably_unspendable(&self) -> bool {
!self.0.is_empty() && (opcodes::All::from(self.0[0]).classify() == opcodes::Class::ReturnOp ||
opcodes::All::from(self.0[0]).classify() == opcodes::Class::IllegalOp)
}
}
impl Default for Script {
fn default() -> Script { Script(vec![].into_boxed_slice()) }
}
impl From<Vec<u8>> for Script {
fn from(v: Vec<u8>) -> Script { Script(v.into_boxed_slice()) }
}
impl_index_newtype!(Script, u8);
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Instruction<'a> {
PushBytes(&'a [u8]),
Op(opcodes::All),
Error(Error)
}
pub struct Instructions<'a> {
data: &'a [u8]
}
impl<'a> IntoIterator for &'a Script {
type Item = Instruction<'a>;
type IntoIter = Instructions<'a>;
fn into_iter(self) -> Instructions<'a> { Instructions { data: &self.0[..] } }
}
impl<'a> Iterator for Instructions<'a> {
type Item = Instruction<'a>;
fn next(&mut self) -> Option<Instruction<'a>> {
if self.data.is_empty() {
return None;
}
match opcodes::All::from(self.data[0]).classify() {
opcodes::Class::PushBytes(n) => {
let n = n as usize;
if self.data.len() < n + 1 {
return Some(Instruction::Error(Error::EarlyEndOfScript));
}
let ret = Some(Instruction::PushBytes(&self.data[1..n+1]));
self.data = &self.data[n + 1..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA1) => {
if self.data.len() < 2 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let n = match read_uint(&self.data[1..], 1) {
Ok(n) => n,
Err(e) => { return Some(Instruction::Error(e)); }
};
if self.data.len() < n + 2 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let ret = Some(Instruction::PushBytes(&self.data[2..n+2]));
self.data = &self.data[n + 2..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA2) => {
if self.data.len() < 3 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let n = match read_uint(&self.data[1..], 2) {
Ok(n) => n,
Err(e) => { return Some(Instruction::Error(e)); }
};
if self.data.len() < n + 3 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let ret = Some(Instruction::PushBytes(&self.data[3..n + 3]));
self.data = &self.data[n + 3..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA4) => {
if self.data.len() < 5 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let n = match read_uint(&self.data[1..], 4) {
Ok(n) => n,
Err(e) => { return Some(Instruction::Error(e)); }
};
if self.data.len() < n + 5 { return Some(Instruction::Error(Error::EarlyEndOfScript)); }
let ret = Some(Instruction::PushBytes(&self.data[5..n + 5]));
self.data = &self.data[n + 5..];
ret
}
_ => {
let ret = Some(Instruction::Op(opcodes::All::from(self.data[0])));
self.data = &self.data[1..];
ret
}
}
}
}
impl Builder {
pub fn new() -> Builder { Builder(vec![]) }
pub fn len(&self) -> usize { self.0.len() }
pub fn is_empty(&self) -> bool { self.0.is_empty() }
pub fn push_int(mut self, data: i64) -> Builder {
if data == -1 || (data >= 1 && data <= 16) {
self.0.push((data - 1 + opcodes::OP_TRUE as i64) as u8);
self
}
else if data == 0 {
self.0.push(opcodes::OP_FALSE as u8);
self
}
else { self.push_scriptint(data) }
}
pub fn push_scriptint(self, data: i64) -> Builder {
self.push_slice(&build_scriptint(data))
}
pub fn push_slice(mut self, data: &[u8]) -> Builder {
match data.len() {
n if n < opcodes::Ordinary::OP_PUSHDATA1 as usize => { self.0.push(n as u8); },
n if n < 0x100 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA1 as u8);
self.0.push(n as u8);
},
n if n < 0x10000 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA2 as u8);
self.0.push((n % 0x100) as u8);
self.0.push((n / 0x100) as u8);
},
n if n < 0x100000000 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA4 as u8);
self.0.push((n % 0x100) as u8);
self.0.push(((n / 0x100) % 0x100) as u8);
self.0.push(((n / 0x10000) % 0x100) as u8);
self.0.push((n / 0x1000000) as u8);
}
_ => panic!("tried to put a 4bn+ sized object into a script!")
}
self.0.extend(data.iter().cloned());
self
}
pub fn push_opcode(mut self, data: opcodes::All) -> Builder {
self.0.push(data as u8);
self
}
pub fn into_script(self) -> Script {
Script(self.0.into_boxed_slice())
}
}
impl Default for Builder {
fn default() -> Builder { Builder(vec![]) }
}
impl From<Vec<u8>> for Builder {
fn from(v: Vec<u8>) -> Builder { Builder(v) }
}
impl_index_newtype!(Builder, u8);
impl serde::Serialize for Script {
fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
where S: serde::Serializer,
{
s.visit_str(&format!("{:x}", self))
}
}
impl serde::Deserialize for Script {
fn deserialize<D>(d: &mut D) -> Result<Script, D::Error>
where D: serde::Deserializer
{
use serialize::hex::FromHex;
struct ScriptVisitor;
impl serde::de::Visitor for ScriptVisitor {
type Value = Script;
fn visit_string<E>(&mut self, v: String) -> Result<Script, E>
where E: serde::de::Error
{
self.visit_str(&v)
}
fn visit_str<E>(&mut self, hex_str: &str) -> Result<Script, E>
where E: serde::de::Error
{
let raw_vec: Vec<u8> = try!(hex_str.from_hex()
.map_err(|_| serde::de::Error::syntax("bad script hex")));
Ok(Script::from(raw_vec))
}
}
d.visit(ScriptVisitor)
}
}
impl<S: SimpleEncoder> ConsensusEncodable<S> for Script {
#[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
self.0.consensus_encode(s)
}
}
impl<D: SimpleDecoder> ConsensusDecodable<D> for Script {
#[inline]
fn consensus_decode(d: &mut D) -> Result<Script, D::Error> {
Ok(Script(try!(ConsensusDecodable::consensus_decode(d))))
}
}
#[cfg(test)]
mod test {
use serialize::hex::FromHex;
use super::*;
use super::build_scriptint;
use network::serialize::{deserialize, serialize};
use blockdata::opcodes;
#[test]
fn script() {
let mut comp = vec![];
let mut script = Builder::new();
assert_eq!(&script[..], &comp[..]);
script = script.push_int(1); comp.push(81u8); assert_eq!(&script[..], &comp[..]);
script = script.push_int(0); comp.push(0u8); assert_eq!(&script[..], &comp[..]);
script = script.push_int(4); comp.push(84u8); assert_eq!(&script[..], &comp[..]);
script = script.push_int(-1); comp.push(79u8); assert_eq!(&script[..], &comp[..]);
script = script.push_scriptint(4); comp.extend([1u8, 4].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_int(17); comp.extend([1u8, 17].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_slice("NRA4VR".as_bytes()); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().cloned()); assert_eq!(&script[..], &comp[..]);
script = script.push_opcode(opcodes::All::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
script = script.push_opcode(opcodes::All::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
}
#[test]
fn script_builder() {
let script = Builder::new().push_opcode(opcodes::All::OP_DUP)
.push_opcode(opcodes::All::OP_HASH160)
.push_slice(&"16e1ae70ff0fa102905d4af297f6912bda6cce19".from_hex().unwrap())
.push_opcode(opcodes::All::OP_EQUALVERIFY)
.push_opcode(opcodes::All::OP_CHECKSIG)
.into_script();
assert_eq!(&format!("{:x}", script), "76a91416e1ae70ff0fa102905d4af297f6912bda6cce1988ac");
}
#[test]
fn script_serialize() {
let hex_script = "6c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52".from_hex().unwrap();
let script: Result<Script, _> = deserialize(&hex_script);
assert!(script.is_ok());
assert_eq!(serialize(&script.unwrap()).ok(), Some(hex_script));
}
#[test]
fn scriptint_round_trip() {
assert_eq!(build_scriptint(-1), vec![0x81]);
assert_eq!(build_scriptint(255), vec![255, 0]);
assert_eq!(build_scriptint(256), vec![0, 1]);
assert_eq!(build_scriptint(257), vec![1, 1]);
assert_eq!(build_scriptint(511), vec![255, 1]);
for &i in [10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000,
(1 << 31) - 1, -((1 << 31) - 1)].iter() {
assert_eq!(Ok(i), read_scriptint(&build_scriptint(i)));
assert_eq!(Ok(-i), read_scriptint(&build_scriptint(-i)));
}
assert!(read_scriptint(&build_scriptint(1 << 31)).is_err());
assert!(read_scriptint(&build_scriptint(-(1 << 31))).is_err());
}
macro_rules! hex_script (($s:expr) => (Script::from($s.from_hex().unwrap())));
#[test]
fn provably_unspendable_test() {
assert_eq!(hex_script!("410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac").is_provably_unspendable(), false);
assert_eq!(hex_script!("4104ea1feff861b51fe3f5f8a3b12d0f4712db80e919548a80839fc47c6a21e66d957e9c5d8cd108c7a2d2324bad71f9904ac0ae7336507d785b17a2c115e427a32fac").is_provably_unspendable(), false);
assert_eq!(hex_script!("76a914ee61d57ab51b9d212335b1dba62794ac20d2bcf988ac").is_provably_unspendable(), false);
assert_eq!(hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87").is_provably_unspendable(), true);
}
#[test]
fn script_json_serialize() {
use strason;
let original = hex_script!("827651a0698faaa9a8a7a687");
let json = strason::from_serialize(&original).unwrap();
assert_eq!(json.to_bytes(), b"\"827651a0698faaa9a8a7a687\"");
assert_eq!(json.string(), Some("827651a0698faaa9a8a7a687"));
let des = json.into_deserialize().unwrap();
assert_eq!(original, des);
}
#[test]
fn script_debug_display() {
assert_eq!(format!("{:?}", hex_script!("6363636363686868686800")),
"Script(OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0)");
assert_eq!(format!("{}", hex_script!("6363636363686868686800")),
"Script(OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0)");
assert_eq!(format!("{}", hex_script!("2102715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699ac")),
"Script(OP_PUSHBYTES_33 02715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699 OP_CHECKSIG)");
assert_eq!(format!("{}", hex_script!("0047304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401004cf1552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae")),
"Script(OP_0 OP_PUSHBYTES_71 304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401 OP_0 OP_PUSHDATA1 552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae)");
}
}