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
#![allow(bare_trait_objects)]
#![recursion_limit = "128"]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#![deny(unsafe_code)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![deny(dead_code)]
#![deny(unused_imports)]
#![deny(missing_docs)]
pub extern crate bitcoin;
pub extern crate elements;
#[cfg(feature = "serde")]
pub extern crate serde;
#[cfg(all(test, feature = "unstable"))]
extern crate test;
extern crate miniscript as bitcoin_miniscript;
pub(crate) use bitcoin_miniscript::expression::FromTree as BtcFromTree;
pub(crate) use bitcoin_miniscript::expression::Tree as BtcTree;
pub(crate) use bitcoin_miniscript::policy::semantic::Policy as BtcPolicy;
pub(crate) use bitcoin_miniscript::policy::Liftable as BtcLiftable;
pub(crate) use bitcoin_miniscript::Descriptor as BtcDescriptor;
pub(crate) use bitcoin_miniscript::DescriptorTrait as BtcDescriptorTrait;
pub(crate) use bitcoin_miniscript::Error as BtcError;
pub(crate) use bitcoin_miniscript::Miniscript as BtcMiniscript;
pub(crate) use bitcoin_miniscript::Satisfier as BtcSatisfier;
pub(crate) use bitcoin_miniscript::Segwitv0 as BtcSegwitv0;
pub(crate) use bitcoin_miniscript::Terminal as BtcTerminal;
pub use bitcoin_miniscript::{DummyKey, DummyKeyHash};
pub use bitcoin_miniscript::{
ForEach, ForEachKey, MiniscriptKey, ToPublicKey, TranslatePk, TranslatePk1, TranslatePk2,
TranslatePk3,
};
#[macro_use]
mod macros;
pub mod descriptor;
pub mod expression;
pub mod interpreter;
pub mod miniscript;
pub mod policy;
pub mod pset;
mod util;
use std::{error, fmt, str};
#[allow(deprecated)]
use bitcoin::util::contracthash;
use elements::hashes::sha256;
use elements::{opcodes, script, secp256k1_zkp, secp256k1_zkp::Secp256k1};
pub use descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait};
pub use interpreter::Interpreter;
pub use miniscript::context::{BareCtx, Legacy, ScriptContext, Segwitv0};
pub use miniscript::decode::Terminal;
pub use miniscript::satisfy::{elementssig_from_rawsig, elementssig_to_rawsig};
pub use miniscript::satisfy::{ElementsSig, Preimage32, Satisfier};
pub use miniscript::Miniscript;
pub fn tweak_key<Pk, C: secp256k1_zkp::Verification>(
pk: &Pk,
secp: &Secp256k1<C>,
contract: &[u8],
) -> bitcoin::PublicKey
where
Pk: MiniscriptKey + ToPublicKey,
{
let pk = pk.to_public_key();
#[allow(deprecated)]
contracthash::tweak_key(secp, pk, contract)
}
#[derive(Debug)]
pub enum Error {
InvalidOpcode(opcodes::All),
NonMinimalVerify(miniscript::lex::Token),
InvalidPush(Vec<u8>),
Script(script::Error),
CmsTooManyKeys(u32),
Unprintable(u8),
ExpectedChar(char),
UnexpectedStart,
Unexpected(String),
MultiColon(String),
MultiAt(String),
AtOutsideOr(String),
NonCanonicalTrue,
NonCanonicalFalse,
LikelyFalse,
UnknownWrapper(char),
NonTopLevel(String),
Trailing(String),
BadPubkey(bitcoin::util::key::Error),
MissingHash(sha256::Hash),
MissingSig(bitcoin::PublicKey),
RelativeLocktimeNotMet(u32),
AbsoluteLocktimeNotMet(u32),
CouldNotSatisfy,
TypeCheck(String),
BadDescriptor(String),
Secp(elements::secp256k1_zkp::Error),
#[cfg(feature = "compiler")]
CompilerError(policy::compiler::CompilerError),
PolicyError(policy::concrete::PolicyError),
LiftError(policy::LiftError),
ContextError(miniscript::context::ScriptContextError),
MaxRecursiveDepthExceeded,
ScriptSizeTooLarge,
NonStandardBareScript,
AnalysisError(miniscript::analyzable::AnalysisError),
ImpossibleSatisfaction,
BareDescriptorAddr,
BtcError(bitcoin_miniscript::Error),
CovError(descriptor::CovError),
}
#[doc(hidden)]
impl<Pk, Ctx> From<miniscript::types::Error<Pk, Ctx>> for Error
where
Pk: MiniscriptKey,
Ctx: ScriptContext,
{
fn from(e: miniscript::types::Error<Pk, Ctx>) -> Error {
Error::TypeCheck(e.to_string())
}
}
#[doc(hidden)]
impl From<bitcoin_miniscript::Error> for Error {
fn from(e: bitcoin_miniscript::Error) -> Error {
Error::BtcError(e)
}
}
#[doc(hidden)]
impl From<policy::LiftError> for Error {
fn from(e: policy::LiftError) -> Error {
Error::LiftError(e)
}
}
#[doc(hidden)]
impl From<miniscript::context::ScriptContextError> for Error {
fn from(e: miniscript::context::ScriptContextError) -> Error {
Error::ContextError(e)
}
}
#[doc(hidden)]
impl From<miniscript::analyzable::AnalysisError> for Error {
fn from(e: miniscript::analyzable::AnalysisError) -> Error {
Error::AnalysisError(e)
}
}
#[doc(hidden)]
impl From<elements::secp256k1_zkp::Error> for Error {
fn from(e: elements::secp256k1_zkp::Error) -> Error {
Error::Secp(e)
}
}
#[doc(hidden)]
impl From<elements::secp256k1_zkp::UpstreamError> for Error {
fn from(e: elements::secp256k1_zkp::UpstreamError) -> Error {
Error::Secp(elements::secp256k1_zkp::Error::Upstream(e))
}
}
#[doc(hidden)]
impl From<bitcoin::util::key::Error> for Error {
fn from(e: bitcoin::util::key::Error) -> Error {
Error::BadPubkey(e)
}
}
fn errstr(s: &str) -> Error {
Error::Unexpected(s.to_owned())
}
impl error::Error for Error {
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::BadPubkey(ref e) => Some(e),
_ => None,
}
}
}
const MAX_RECURSION_DEPTH: u32 = 402;
const MAX_SCRIPT_SIZE: u32 = 10000;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidOpcode(op) => write!(f, "invalid opcode {}", op),
Error::NonMinimalVerify(ref tok) => write!(f, "{} VERIFY", tok),
Error::InvalidPush(ref push) => write!(f, "invalid push {:?}", push),
Error::Script(ref e) => fmt::Display::fmt(e, f),
Error::CmsTooManyKeys(n) => write!(f, "checkmultisig with {} keys", n),
Error::Unprintable(x) => write!(f, "unprintable character 0x{:02x}", x),
Error::ExpectedChar(c) => write!(f, "expected {}", c),
Error::UnexpectedStart => f.write_str("unexpected start of script"),
Error::Unexpected(ref s) => write!(f, "unexpected «{}»", s),
Error::MultiColon(ref s) => write!(f, "«{}» has multiple instances of «:»", s),
Error::MultiAt(ref s) => write!(f, "«{}» has multiple instances of «@»", s),
Error::AtOutsideOr(ref s) => write!(f, "«{}» contains «@» in non-or() context", s),
Error::NonCanonicalTrue => f.write_str("Use «t:X» rather than «and_v(X,true())»"),
Error::NonCanonicalFalse => {
f.write_str("Use «u:X» «l:X» rather than «or_i(X,false)» «or_i(false,X)»")
}
Error::LikelyFalse => write!(f, "0 is not very likely (use «u:0»)"),
Error::UnknownWrapper(ch) => write!(f, "unknown wrapper «{}:»", ch),
Error::NonTopLevel(ref s) => write!(f, "non-T miniscript: {}", s),
Error::Trailing(ref s) => write!(f, "trailing tokens: {}", s),
Error::MissingHash(ref h) => write!(f, "missing preimage of hash {}", h),
Error::MissingSig(ref pk) => write!(f, "missing signature for key {:?}", pk),
Error::RelativeLocktimeNotMet(n) => {
write!(f, "required relative locktime CSV of {} blocks, not met", n)
}
Error::AbsoluteLocktimeNotMet(n) => write!(
f,
"required absolute locktime CLTV of {} blocks, not met",
n
),
Error::CouldNotSatisfy => f.write_str("could not satisfy"),
Error::BadPubkey(ref e) => fmt::Display::fmt(e, f),
Error::TypeCheck(ref e) => write!(f, "typecheck: {}", e),
Error::BadDescriptor(ref e) => write!(f, "Invalid descriptor: {}", e),
Error::Secp(ref e) => fmt::Display::fmt(e, f),
Error::ContextError(ref e) => fmt::Display::fmt(e, f),
#[cfg(feature = "compiler")]
Error::CompilerError(ref e) => fmt::Display::fmt(e, f),
Error::PolicyError(ref e) => fmt::Display::fmt(e, f),
Error::LiftError(ref e) => fmt::Display::fmt(e, f),
Error::MaxRecursiveDepthExceeded => write!(
f,
"Recursive depth over {} not permitted",
MAX_RECURSION_DEPTH
),
Error::ScriptSizeTooLarge => write!(
f,
"Standardness rules imply bitcoin than {} bytes",
MAX_SCRIPT_SIZE
),
Error::NonStandardBareScript => write!(
f,
"Anything but c:pk(key) (P2PK), c:pk_h(key) (P2PKH), and thresh_m(k,...) \
up to n=3 is invalid by standardness (bare).
"
),
Error::AnalysisError(ref e) => e.fmt(f),
Error::ImpossibleSatisfaction => write!(f, "Impossible to satisfy Miniscript"),
Error::BareDescriptorAddr => write!(f, "Bare descriptors don't have address"),
Error::BtcError(ref e) => write!(f, " Bitcoin Miniscript Error {}", e),
Error::CovError(ref e) => write!(f, "Covenant Error: {}", e),
}
}
}
#[doc(hidden)]
#[cfg(feature = "compiler")]
impl From<policy::compiler::CompilerError> for Error {
fn from(e: policy::compiler::CompilerError) -> Error {
Error::CompilerError(e)
}
}
#[doc(hidden)]
impl From<policy::concrete::PolicyError> for Error {
fn from(e: policy::concrete::PolicyError) -> Error {
Error::PolicyError(e)
}
}
pub fn script_num_size(n: usize) -> usize {
match n {
n if n <= 0x10 => 1,
n if n < 0x80 => 2,
n if n < 0x8000 => 3,
n if n < 0x800000 => 4,
n if n < 0x80000000 => 5,
_ => 6,
}
}
fn push_opcode_size(script_size: usize) -> usize {
if script_size < 76 {
1
} else if script_size < 0x100 {
2
} else if script_size < 0x10000 {
3
} else {
5
}
}
#[cfg(test)]
fn hex_script(s: &str) -> elements::Script {
let v: Vec<u8> = elements::hashes::hex::FromHex::from_hex(s).unwrap();
elements::Script::from(v)
}