use crate::{hash::sha256, Error, PublicKey, Result};
pub const MAX_ENCODED: usize = 1024;
pub const MAX_DEPTH: usize = 4;
pub const MAX_NODES: usize = 32;
pub const MAX_KEYS: usize = 32;
pub const MAX_MULTISIG_N: usize = 16;
pub const MAX_PREIMAGE_LEN: usize = 64;
const TAG_SIG: u8 = 0x01;
const TAG_MULTISIG: u8 = 0x02;
const TAG_HEIGHT: u8 = 0x03;
const TAG_RELATIVE: u8 = 0x04;
const TAG_HASHLOCK: u8 = 0x05;
const TAG_AND: u8 = 0x10;
const TAG_OR: u8 = 0x11;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Condition {
Signature(PublicKey),
Multisig {
required: u8,
keys: Vec<PublicKey>,
},
AbsoluteHeight(u64),
RelativeBlocks(u32),
Hashlock([u8; 32]),
And(Vec<Condition>),
Or(Vec<Condition>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EscrowRefundTemplate {
pub release_required: u8,
pub release_keys: Vec<PublicKey>,
pub refund_key: PublicKey,
pub refund_height: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HtlcTemplate {
pub recipient_key: PublicKey,
pub refund_key: PublicKey,
pub secret_hash: [u8; 32],
pub refund_height: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaymentChannelTemplate {
pub participant_keys: Vec<PublicKey>,
pub required: u8,
pub relative_blocks: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct ConditionTemplates;
impl ConditionTemplates {
pub fn treasury_multisig(required: u8, keys: Vec<PublicKey>) -> Condition {
Condition::multisig(required, keys)
}
pub fn vesting(owner_key: PublicKey, unlock_height: u64) -> Condition {
Condition::all(vec![
Condition::signature(owner_key),
Condition::absolute_height(unlock_height),
])
}
pub fn escrow_refund(p: EscrowRefundTemplate) -> Condition {
Condition::any(vec![
Condition::multisig(p.release_required, p.release_keys),
Condition::all(vec![
Condition::signature(p.refund_key),
Condition::absolute_height(p.refund_height),
]),
])
}
pub fn htlc(p: HtlcTemplate) -> Condition {
Condition::any(vec![
Condition::all(vec![
Condition::signature(p.recipient_key),
Condition::hashlock(p.secret_hash),
]),
Condition::all(vec![
Condition::signature(p.refund_key),
Condition::absolute_height(p.refund_height),
]),
])
}
pub fn payment_channel(p: PaymentChannelTemplate) -> Condition {
let required = if p.required == 0 {
p.participant_keys.len() as u8
} else {
p.required
};
Condition::all(vec![
Condition::multisig(required, p.participant_keys),
Condition::relative_blocks(p.relative_blocks),
])
}
}
impl Condition {
pub fn decode(bytes: &[u8]) -> Result<Self> {
let c = Self::decode_fragment(bytes)?;
if !c.requires_signature() {
return Err(Error::InvalidCondition(
"a spending path does not require any signature".into(),
));
}
Ok(c)
}
pub fn decode_fragment(bytes: &[u8]) -> Result<Self> {
if bytes.is_empty() || bytes.len() > MAX_ENCODED {
return Err(Error::InvalidCondition(format!(
"encoding is {} bytes, must be 1..{MAX_ENCODED}",
bytes.len()
)));
}
let mut d = Decoder {
bytes,
pos: 0,
nodes: 0,
};
let c = d.node(1)?;
if d.pos != bytes.len() {
return Err(Error::InvalidCondition(format!(
"{} trailing bytes",
bytes.len() - d.pos
)));
}
c.validate_structure()?;
if c.encode()? != bytes {
return Err(Error::InvalidCondition("non-canonical encoding".into()));
}
Ok(c)
}
pub fn decode_hex(hex_text: &str) -> Result<Self> {
let bytes =
hex::decode(hex_text).map_err(|_| Error::InvalidCondition("invalid condition hex".into()))?;
Self::decode(&bytes)
}
pub fn decode_fragment_hex(hex_text: &str) -> Result<Self> {
let bytes =
hex::decode(hex_text).map_err(|_| Error::InvalidCondition("invalid condition hex".into()))?;
Self::decode_fragment(&bytes)
}
pub fn signature(public_key: PublicKey) -> Self {
Self::Signature(public_key)
}
pub fn multisig(required: u8, keys: Vec<PublicKey>) -> Self {
Self::Multisig { required, keys }
}
pub fn absolute_height(height: u64) -> Self {
Self::AbsoluteHeight(height)
}
pub fn relative_blocks(blocks: u32) -> Self {
Self::RelativeBlocks(blocks)
}
pub fn hashlock(hash: [u8; 32]) -> Self {
Self::Hashlock(hash)
}
pub fn hashlock_secret(secret: &[u8]) -> Result<Self> {
if secret.is_empty() || secret.len() > MAX_PREIMAGE_LEN {
return Err(Error::InvalidCondition("invalid hashlock preimage length".into()));
}
Ok(Self::Hashlock(sha256(secret)))
}
pub fn all(children: Vec<Condition>) -> Self {
Self::And(children)
}
pub fn any(children: Vec<Condition>) -> Self {
Self::Or(children)
}
pub fn encode(&self) -> Result<Vec<u8>> {
let c = self.canonicalized();
c.validate_structure()?;
let mut out = Vec::new();
c.encode_into(&mut out);
if out.len() > MAX_ENCODED {
return Err(Error::InvalidCondition(format!(
"encoding larger than {MAX_ENCODED} bytes"
)));
}
Ok(out)
}
pub fn encode_hex(&self) -> Result<String> {
Ok(hex::encode(self.encode()?))
}
pub fn condition_hash(&self) -> Result<[u8; 32]> {
Ok(sha256(&self.encode()?))
}
fn canonicalized(&self) -> Self {
match self {
Self::Multisig { required, keys } => {
let mut keys = keys.clone();
keys.sort_by_key(|k| k.to_bytes());
Self::Multisig {
required: *required,
keys,
}
}
Self::And(children) => Self::And(children.iter().map(Self::canonicalized).collect()),
Self::Or(children) => Self::Or(children.iter().map(Self::canonicalized).collect()),
other => other.clone(),
}
}
fn encode_into(&self, out: &mut Vec<u8>) {
match self {
Self::Signature(key) => {
out.push(TAG_SIG);
out.extend_from_slice(&key.to_bytes());
}
Self::Multisig { required, keys } => {
out.push(TAG_MULTISIG);
out.push(*required);
out.push(keys.len() as u8);
for key in keys {
out.extend_from_slice(&key.to_bytes());
}
}
Self::AbsoluteHeight(height) => {
out.push(TAG_HEIGHT);
out.extend_from_slice(&height.to_be_bytes());
}
Self::RelativeBlocks(blocks) => {
out.push(TAG_RELATIVE);
out.extend_from_slice(&blocks.to_be_bytes());
}
Self::Hashlock(hash) => {
out.push(TAG_HASHLOCK);
out.extend_from_slice(hash);
}
Self::And(children) => {
out.push(TAG_AND);
out.push(children.len() as u8);
for child in children {
child.encode_into(out);
}
}
Self::Or(children) => {
out.push(TAG_OR);
out.push(children.len() as u8);
for child in children {
child.encode_into(out);
}
}
}
}
fn validate_structure(&self) -> Result<()> {
let mut stats = Stats::default();
self.validate_inner(1, &mut stats)?;
Ok(())
}
fn validate_inner(&self, depth: usize, stats: &mut Stats) -> Result<()> {
if depth > MAX_DEPTH {
return Err(Error::InvalidCondition(format!("deeper than {MAX_DEPTH}")));
}
stats.nodes += 1;
if stats.nodes > MAX_NODES {
return Err(Error::InvalidCondition(format!("more than {MAX_NODES} nodes")));
}
match self {
Self::Signature(_) => {
stats.keys += 1;
}
Self::Multisig { required, keys } => {
if keys.is_empty()
|| keys.len() > MAX_MULTISIG_N
|| *required == 0
|| *required as usize > keys.len()
{
return Err(Error::InvalidCondition("invalid multisig threshold".into()));
}
stats.keys += keys.len();
for pair in keys.windows(2) {
if pair[0].to_bytes() >= pair[1].to_bytes() {
return Err(Error::InvalidCondition(
"multisig keys must be strictly ascending".into(),
));
}
}
}
Self::AbsoluteHeight(_) | Self::Hashlock(_) => {}
Self::RelativeBlocks(blocks) => {
if *blocks == 0 || *blocks > 1_000_000 {
return Err(Error::InvalidCondition("invalid relative lock".into()));
}
}
Self::And(children) | Self::Or(children) => {
if children.len() < 2 || children.len() > 8 {
return Err(Error::InvalidCondition("invalid child count".into()));
}
for child in children {
child.validate_inner(depth + 1, stats)?;
}
}
}
if stats.keys > MAX_KEYS {
return Err(Error::InvalidCondition(format!("more than {MAX_KEYS} keys")));
}
Ok(())
}
fn requires_signature(&self) -> bool {
match self {
Self::Signature(_) | Self::Multisig { .. } => true,
Self::AbsoluteHeight(_) | Self::RelativeBlocks(_) | Self::Hashlock(_) => false,
Self::And(children) => children.iter().any(Self::requires_signature),
Self::Or(children) => children.iter().all(Self::requires_signature),
}
}
}
#[derive(Default)]
struct Stats {
nodes: usize,
keys: usize,
}
struct Decoder<'a> {
bytes: &'a [u8],
pos: usize,
nodes: usize,
}
impl<'a> Decoder<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
if self.pos + n > self.bytes.len() {
return Err(Error::InvalidCondition("truncated".into()));
}
let out = &self.bytes[self.pos..self.pos + n];
self.pos += n;
Ok(out)
}
fn node(&mut self, depth: usize) -> Result<Condition> {
if depth > MAX_DEPTH {
return Err(Error::InvalidCondition(format!("deeper than {MAX_DEPTH}")));
}
self.nodes += 1;
if self.nodes > MAX_NODES {
return Err(Error::InvalidCondition(format!("more than {MAX_NODES} nodes")));
}
let tag = self.take(1)?[0];
match tag {
TAG_SIG => Ok(Condition::Signature(
PublicKey::from_bytes(self.take(32)?)
.map_err(|_| Error::InvalidCondition("invalid public key".into()))?,
)),
TAG_MULTISIG => {
let required = self.take(1)?[0];
let count = self.take(1)?[0] as usize;
let mut keys = Vec::with_capacity(count);
for _ in 0..count {
keys.push(
PublicKey::from_bytes(self.take(32)?)
.map_err(|_| Error::InvalidCondition("invalid public key".into()))?,
);
}
Ok(Condition::Multisig { required, keys })
}
TAG_HEIGHT => {
let mut b = [0u8; 8];
b.copy_from_slice(self.take(8)?);
Ok(Condition::AbsoluteHeight(u64::from_be_bytes(b)))
}
TAG_RELATIVE => {
let mut b = [0u8; 4];
b.copy_from_slice(self.take(4)?);
Ok(Condition::RelativeBlocks(u32::from_be_bytes(b)))
}
TAG_HASHLOCK => {
let mut h = [0u8; 32];
h.copy_from_slice(self.take(32)?);
Ok(Condition::Hashlock(h))
}
TAG_AND | TAG_OR => {
let count = self.take(1)?[0] as usize;
let mut children = Vec::with_capacity(count);
for _ in 0..count {
children.push(self.node(depth + 1)?);
}
if tag == TAG_AND {
Ok(Condition::And(children))
} else {
Ok(Condition::Or(children))
}
}
other => Err(Error::InvalidCondition(format!("unknown tag 0x{other:02x}"))),
}
}
}