bitcoin-script
Bitcoin scripts inline in Rust.
Usage
This crate exports a bitcoin_script!
macro which can be used to build Bitcoin scripts. The macro returns the Script
type from the bitcoin
crate.
Example:
use bitcoin_script;
let htlc_script = bitcoin_script! ;
NOTE: As of rustc 1.41, the Rust compiler prevents using procedural macros as expressions. To use this macro you'll need to be on nightly and add #![feature(proc_macro_hygiene)]
to the root of your crate. This will be stablized in the near future, the PR can be found here: https://github.com/rust-lang/rust/pull/68717
Syntax
Scripts are based on the standard syntax made up of opcodes, base-10 integers, or hex string literals. Additionally, Rust expressions can be interpolated in order to support dynamically capturing Rust variables or computing values (delimited by <angle brackets>
).
Whitespace is ignored - scripts can be formatted in the author's preferred style.
Opcodes
All normal opcodes are available, in the form OP_X
.
let script = bitcoin_script!;
Integer Literals
Positive and negative 64-bit integer literals can be used, and will resolve to their most efficient encoding.
For example:
2
will resolve toOP_PUSHNUM_2
(0x52
)255
will resolve to a length-delimited varint:0x02ff00
(note the extra zero byte, due to the way Bitcoin scripts use the most-significant bit to represent the sign)`
let script = bitcoin_script!;
Hex Literals
Hex strings can be specified, prefixed with 0x
.
let script = bitcoin_script!;
Escape Sequences
Dynamic Rust expressions are supported inside the script, surrounded by angle brackets. In many cases, this will just be a variable identifier, but this can also be a function call or arithmetic.
Rust expressions of the following types are supported:
i64
Vec<u8>
bitcoin::PublicKey
let bytes = vec!;
let script = bitcoin_script! ;