Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements and fixes for primitive types #2 #54

Merged
merged 20 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
323c75a
primitives: add checked Sats arithmetic operations
dr-orlovsky Aug 7, 2023
4efb8f1
primitives: add serde to BlockHeader
dr-orlovsky Aug 11, 2023
c7bc133
primitives: impl FromStr for Outpoint
dr-orlovsky Aug 11, 2023
6051799
primitives: rename all serde fields to camelCase
dr-orlovsky Aug 11, 2023
fdf4167
primitives: export OutpointParseError
dr-orlovsky Aug 11, 2023
b0c8538
primitives: fix WitnessVer::from_version_no
dr-orlovsky Aug 11, 2023
58cf4b1
primitives: add Chain::is_testnet method
dr-orlovsky Sep 18, 2023
25a11b3
primitives: export ChainParseError
dr-orlovsky Sep 18, 2023
9f636cf
chore: update to amplify v4.1.0
dr-orlovsky Sep 19, 2023
272faaf
primitives: fix Txid and BlockHash types serde serialization
dr-orlovsky Sep 19, 2023
133cbbe
primitives: impl FromHex for script types
dr-orlovsky Sep 19, 2023
75595c4
primitives: move ScriptBytes to script module
dr-orlovsky Sep 19, 2023
64649c0
primitives: custom serde implementation for ScriptBytes
dr-orlovsky Sep 19, 2023
30d4db7
primitives: add ScriptBytes::into_vec method
dr-orlovsky Sep 19, 2023
2815ea6
primitives: add Witness default constructors
dr-orlovsky Sep 19, 2023
0453d78
primitives: custom Witness serde implementation
dr-orlovsky Sep 19, 2023
6b2e0da
primitives: add Outpoint::vout_u32 convenience method
dr-orlovsky Sep 19, 2023
64477b5
primitives: improvements to Sats API
dr-orlovsky Sep 20, 2023
13aa032
primitives: add Outpoint and Vout convertors to usize
dr-orlovsky Sep 20, 2023
263d48e
primitives: add LockTime API
dr-orlovsky Sep 20, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 9 additions & 34 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ edition = "2021"
license = "Apache-2.0"

[workspace.dependencies]
amplify = "4.0.1"
amplify = "4.0.2"
strict_encoding = "2.5.0"
commit_verify = "0.10.5"
single_use_seals = "0.10.0"
Expand Down Expand Up @@ -72,3 +72,7 @@ stl = ["strict_types", "strict_types/base64", "bp-primitives/stl", "commit_verif

[package.metadata.docs.rs]
features = [ "all" ]

[patch.crates-io]
amplify = { git = "https://github.com/rust-amplify/rust-amplify", branch = "feat/array-reverse" }
strict_encoding = { git = "https://github.com/strict-types/strict-encoding", branch = "chore/amplify-4.1.0" }
23 changes: 17 additions & 6 deletions primitives/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,39 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use amplify::{Bytes32, Wrapper};
use amplify::hex::{self, FromHex};
use amplify::{Bytes32, Bytes32StrRev, Wrapper};

use crate::LIB_NAME_BITCOIN;

#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Display, From)]
#[display(LowerHex)]
#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_BITCOIN)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[wrapper(BorrowSlice, Index, RangeOps)]
#[wrapper(BorrowSlice, Index, RangeOps, Debug, LowerHex, UpperHex, Display, FromStr)]
pub struct BlockHash(
#[from]
#[from([u8; 32])]
Bytes32,
Bytes32StrRev,
);
impl_sha256d_hashtype!(BlockHash, "BlockHash");

impl FromHex for BlockHash {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where I: Iterator<Item = Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator {
Bytes32StrRev::from_byte_iter(iter).map(Self)
}
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", rename_all = "camelCase")
)]
pub struct BlockHeader {
/// Block version, now repurposed for soft fork signalling.
pub version: i32,
Expand Down
107 changes: 7 additions & 100 deletions primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ extern crate serde_crate as serde;
/// Re-export of `secp256k1` crate.
pub extern crate secp256k1;

#[macro_use]
mod macros;
mod block;
pub mod opcodes;
mod script;
Expand All @@ -57,111 +55,20 @@ mod util;
pub mod stl;

pub use block::{BlockHash, BlockHeader};
pub use script::{OpCode, ScriptPubkey, SigScript};
pub use script::{OpCode, ScriptBytes, ScriptPubkey, SigScript};
pub use segwit::*;
pub use taproot::*;
pub use tx::{LockTime, Outpoint, Sats, SeqNo, Tx, TxIn, TxOut, TxVer, Txid, Vout, Witness};
pub use types::{ScriptBytes, VarIntArray};
pub use util::{Chain, NonStandardValue};
pub use tx::{
LockTime, Outpoint, OutpointParseError, Sats, SeqNo, Tx, TxIn, TxOut, TxVer, Txid, Vout,
Witness, LOCKTIME_THRESHOLD,
};
pub use types::VarIntArray;
pub use util::{Chain, ChainParseError, NonStandardValue};

pub const LIB_NAME_BITCOIN: &str = "Bitcoin";

mod types {
use std::fmt::{Formatter, LowerHex, UpperHex};

use amplify::confinement::{Confined, U32};
use amplify::hex::ToHex;

use super::LIB_NAME_BITCOIN;
use crate::opcodes::*;

pub type VarIntArray<T> = Confined<Vec<T>, 0, U32>;

#[derive(
Wrapper, WrapperMut, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Debug, From
)]
#[derive(StrictType, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_BITCOIN)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[wrapper(Deref, Index, RangeOps, BorrowSlice)]
#[wrapper_mut(DerefMut, IndexMut, RangeMut, BorrowSliceMut)]
pub struct ScriptBytes(VarIntArray<u8>);

impl From<Vec<u8>> for ScriptBytes {
fn from(value: Vec<u8>) -> Self { Self(Confined::try_from(value).expect("u64 >= usize")) }
}

impl LowerHex for ScriptBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.as_inner().to_hex())
}
}

impl UpperHex for ScriptBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.as_inner().to_hex().to_uppercase())
}
}

impl ScriptBytes {
/// Adds instructions to push some arbitrary data onto the stack.
///
/// ## Panics
///
/// The method panics if `data` length is greater or equal to
/// 0x100000000.
pub fn push_slice(&mut self, data: &[u8]) {
// Start with a PUSH opcode
match data.len() as u64 {
n if n < OP_PUSHDATA1 as u64 => {
self.push(n as u8);
}
n if n < 0x100 => {
self.push(OP_PUSHDATA1);
self.push(n as u8);
}
n if n < 0x10000 => {
self.push(OP_PUSHDATA2);
self.push((n % 0x100) as u8);
self.push((n / 0x100) as u8);
}
n if n < 0x100000000 => {
self.push(OP_PUSHDATA4);
self.push((n % 0x100) as u8);
self.push(((n / 0x100) % 0x100) as u8);
self.push(((n / 0x10000) % 0x100) as u8);
self.push((n / 0x1000000) as u8);
}
_ => panic!("tried to put a 4bn+ sized object into a script!"),
}
// Then push the raw bytes
self.extend(data);
}

#[inline]
fn push(&mut self, data: u8) { self.0.push(data).expect("script exceeds 4GB") }

#[inline]
fn extend(&mut self, data: &[u8]) {
self.0
.extend(data.iter().copied())
.expect("script exceeds 4GB")
}

/// Computes the sum of `len` and the lenght of an appropriate push
/// opcode.
pub fn len_for_slice(len: usize) -> usize {
len + match len {
0..=0x4b => 1,
0x4c..=0xff => 2,
0x100..=0xffff => 3,
// we don't care about oversized, the other fn will panic anyway
_ => 5,
}
}
}
}
74 changes: 0 additions & 74 deletions primitives/src/macros.rs

This file was deleted.

Loading