use crate::primitives::bsv::sighash::SIGHASH_FORKID;
use crate::primitives::ec::signature_der;
use crate::primitives::ec::Signature;
use crate::primitives::BigNumber;
#[path = "der_lax.rs"]
mod der_lax;
pub(super) struct ScriptSignature {
pub(super) signature: Signature,
pub(super) scope: u32,
pub(super) low_s: bool,
}
impl ScriptSignature {
pub(super) fn has_forkid(&self) -> bool {
self.scope & SIGHASH_FORKID != 0
}
}
fn at_most_half_order(s: &[u8; 32]) -> bool {
Signature::new([1; 32], *s).is_low_s()
}
fn at_or_above_order(v: &[u8]) -> bool {
BigNumber::from_bytes_be(v) >= BigNumber::secp256k1_order()
}
fn blank() -> ScriptSignature {
let mut one = [0u8; 32];
one[31] = 1;
ScriptSignature {
signature: Signature::new(one, one),
scope: 1,
low_s: true,
}
}
pub(super) fn under_word(checksig: &[u8]) -> Option<ScriptSignature> {
let Some((&scope, der)) = checksig.split_last() else {
return Some(blank());
};
let (r, s) = der_lax::parse(der)?;
Some(ScriptSignature {
signature: Signature::new(r, s),
scope: u32::from(scope),
low_s: at_most_half_order(&s),
})
}
pub(super) fn by_default(checksig: &[u8]) -> Result<ScriptSignature, &'static str> {
let Some((&scope, der)) = checksig.split_last() else {
return Ok(blank());
};
let read = signature_der::read(der)?;
let slot = |v: &[u8]| -> Option<[u8; 32]> {
let mut out = [0u8; 32];
out.get_mut(32usize.checked_sub(v.len())?..)?
.copy_from_slice(v);
Some(out)
};
let (signature, low_s) = match (slot(read.r), slot(read.s)) {
(Some(r), Some(s)) => (
Signature::new(r, s),
at_most_half_order(&s) || at_or_above_order(&r) || at_or_above_order(&s),
),
(_, s) => (
Signature::new([0; 32], [0; 32]),
s.is_some_and(|s| at_most_half_order(&s) || at_or_above_order(&s)),
),
};
Ok(ScriptSignature {
signature,
scope: u32::from(scope),
low_s,
})
}
impl super::Spend {
pub(super) fn read_signature(&self, sig: &[u8]) -> Option<ScriptSignature> {
if self.flags.is_some() {
under_word(sig)
} else {
by_default(sig).ok()
}
}
}