Skip to content

Commit

Permalink
Merge pull request #91 from Rigidity/sage
Browse files Browse the repository at this point in the history
  • Loading branch information
Rigidity authored Sep 8, 2024
2 parents da42dcb + d3ab5ee commit 1461c0e
Show file tree
Hide file tree
Showing 13 changed files with 183 additions and 402 deletions.
260 changes: 7 additions & 253 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,6 @@ flate2 = "1.0.30"
once_cell = "1.19.0"
num-bigint = "0.4.6"
rstest = "0.22.0"
serde = "1.0.209"
serde_with = "3.9.0"
tracing = "0.1.40"
syn = "2.0.76"
quote = "1.0.37"
Expand Down
2 changes: 0 additions & 2 deletions crates/chia-sdk-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ native-tls = { workspace = true, optional = true }
rustls = { workspace = true, optional = true, features = ["aws_lc_rs"] }
rustls-pemfile = { workspace = true, optional = true }
tracing = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_with = { workspace = true, features = ["hex"] }
futures-util = { workspace = true }
tokio-tungstenite = { workspace = true }
hex = { workspace = true }
8 changes: 4 additions & 4 deletions crates/chia-sdk-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ use chia_protocol::Message;
use tokio::sync::{mpsc, Mutex};
use tokio_tungstenite::Connector;

use crate::{connect_peer, ClientError, Network, NetworkId, Peer};
use crate::{connect_peer, ClientError, Network, Peer};

#[derive(Clone)]
pub struct Client {
network_id: NetworkId,
network_id: String,
network: Network,
connector: Connector,
state: Arc<Mutex<ClientState>>,
Expand Down Expand Up @@ -47,7 +47,7 @@ pub struct ClientState {
}

impl Client {
pub fn new(network_id: NetworkId, network: Network, connector: Connector) -> Self {
pub fn new(network_id: String, network: Network, connector: Connector) -> Self {
Self {
network_id,
network,
Expand All @@ -56,7 +56,7 @@ impl Client {
}
}

pub fn network_id(&self) -> &NetworkId {
pub fn network_id(&self) -> &str {
&self.network_id
}

Expand Down
8 changes: 4 additions & 4 deletions crates/chia-sdk-client/src/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ use tokio::sync::mpsc;
use tokio_tungstenite::Connector;
use tracing::instrument;

use crate::{ClientError, NetworkId, Peer};
use crate::{ClientError, Peer};

#[instrument(skip(connector))]
pub async fn connect_peer(
network_id: NetworkId,
network_id: String,
connector: Connector,
socket_addr: SocketAddr,
) -> Result<(Peer, mpsc::Receiver<Message>), ClientError> {
let (peer, mut receiver) = Peer::connect(socket_addr, connector).await?;

peer.send(Handshake {
network_id: network_id.to_string(),
network_id: network_id.clone(),
protocol_version: "0.0.37".to_string(),
software_version: "0.0.0".to_string(),
server_port: 0,
Expand Down Expand Up @@ -50,7 +50,7 @@ pub async fn connect_peer(
));
}

if handshake.network_id != network_id.to_string() {
if handshake.network_id != network_id {
return Err(ClientError::WrongNetwork(
network_id.to_string(),
handshake.network_id,
Expand Down
31 changes: 2 additions & 29 deletions crates/chia-sdk-client/src/network.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,16 @@
use std::{fmt, net::SocketAddr, time::Duration};
use std::{net::SocketAddr, time::Duration};

use chia_protocol::Bytes32;
use chia_sdk_types::{MAINNET_CONSTANTS, TESTNET11_CONSTANTS};
use futures_util::{stream::FuturesUnordered, StreamExt};
use serde::{Deserialize, Serialize};
use serde_with::{hex::Hex, serde_as};
use tracing::{info, instrument, warn};

use crate::ClientError;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NetworkId {
Mainnet,
Testnet11,
Simulator0,
Custom(String),
}

impl fmt::Display for NetworkId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NetworkId::Mainnet => write!(f, "mainnet"),
NetworkId::Testnet11 => write!(f, "testnet11"),
NetworkId::Simulator0 => write!(f, "simulator0"),
NetworkId::Custom(name) => write!(f, "{name}"),
}
}
}

#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone)]
pub struct Network {
pub default_port: u16,
#[serde_as(as = "Hex")]
pub genesis_challenge: Bytes32,
#[serde_as(as = "Option<Hex>")]
pub agg_sig_me: Option<Bytes32>,
pub dns_introducers: Vec<String>,
}

Expand All @@ -44,7 +19,6 @@ impl Network {
Self {
default_port: 8444,
genesis_challenge: MAINNET_CONSTANTS.genesis_challenge,
agg_sig_me: None,
dns_introducers: vec![
"dns-introducer.chia.net".to_string(),
"chia.ctrlaltdel.ch".to_string(),
Expand All @@ -58,7 +32,6 @@ impl Network {
Self {
default_port: 58444,
genesis_challenge: TESTNET11_CONSTANTS.genesis_challenge,
agg_sig_me: None,
dns_introducers: vec!["dns-introducer-testnet11.chia.net".to_string()],
}
}
Expand Down
83 changes: 83 additions & 0 deletions crates/chia-sdk-signer/src/agg_sig_constants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use chia_consensus::consensus_constants::ConsensusConstants;
use chia_protocol::Bytes32;
use clvmr::sha2::Sha256;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AggSigConstants {
me: Bytes32,
parent: Bytes32,
puzzle: Bytes32,
amount: Bytes32,
parent_amount: Bytes32,
puzzle_amount: Bytes32,
parent_puzzle: Bytes32,
}

impl AggSigConstants {
pub fn new(agg_sig_me: Bytes32) -> Self {
Self {
me: agg_sig_me,
parent: hash(agg_sig_me, 43),
puzzle: hash(agg_sig_me, 44),
amount: hash(agg_sig_me, 45),
puzzle_amount: hash(agg_sig_me, 46),
parent_amount: hash(agg_sig_me, 47),
parent_puzzle: hash(agg_sig_me, 48),
}
}

pub fn me(&self) -> Bytes32 {
self.me
}

pub fn parent(&self) -> Bytes32 {
self.parent
}

pub fn puzzle(&self) -> Bytes32 {
self.puzzle
}

pub fn amount(&self) -> Bytes32 {
self.amount
}

pub fn parent_amount(&self) -> Bytes32 {
self.parent_amount
}

pub fn puzzle_amount(&self) -> Bytes32 {
self.puzzle_amount
}

pub fn parent_puzzle(&self) -> Bytes32 {
self.parent_puzzle
}
}

impl From<&ConsensusConstants> for AggSigConstants {
fn from(constants: &ConsensusConstants) -> Self {
Self {
me: constants.agg_sig_me_additional_data,
parent: constants.agg_sig_parent_additional_data,
puzzle: constants.agg_sig_puzzle_additional_data,
amount: constants.agg_sig_amount_additional_data,
puzzle_amount: constants.agg_sig_puzzle_amount_additional_data,
parent_amount: constants.agg_sig_parent_amount_additional_data,
parent_puzzle: constants.agg_sig_parent_puzzle_additional_data,
}
}
}

impl From<ConsensusConstants> for AggSigConstants {
fn from(constants: ConsensusConstants) -> Self {
Self::from(&constants)
}
}

fn hash(agg_sig_data: Bytes32, byte: u8) -> Bytes32 {
let mut hasher = Sha256::new();
hasher.update(agg_sig_data);
hasher.update([byte]);
hasher.finalize().into()
}
2 changes: 2 additions & 0 deletions crates/chia-sdk-signer/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod agg_sig_constants;
mod error;
mod required_signature;

pub use agg_sig_constants::*;
pub use error::*;
pub use required_signature::*;
27 changes: 14 additions & 13 deletions crates/chia-sdk-signer/src/required_signature.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use chia_bls::PublicKey;
use chia_consensus::consensus_constants::ConsensusConstants;
use chia_protocol::{Bytes, Bytes32, Coin, CoinSpend};
use chia_sdk_types::{run_puzzle, AggSig, AggSigKind, Condition};
use clvm_traits::{FromClvm, ToClvm};
use clvmr::Allocator;

use crate::SignerError;
use crate::{AggSigConstants, SignerError};

#[derive(Debug, Clone)]
pub struct RequiredSignature {
Expand All @@ -17,37 +16,37 @@ pub struct RequiredSignature {

impl RequiredSignature {
/// Converts a known [`AggSig`] condition to a `RequiredSignature` if possible.
pub fn from_condition(coin: &Coin, condition: AggSig, constants: &ConsensusConstants) -> Self {
pub fn from_condition(coin: &Coin, condition: AggSig, constants: &AggSigConstants) -> Self {
let domain_string;

let public_key = condition.public_key;
let message = condition.message;

let appended_info = match condition.kind {
AggSigKind::Parent => {
domain_string = constants.agg_sig_parent_additional_data;
domain_string = constants.parent();
coin.parent_coin_info.to_vec()
}
AggSigKind::Puzzle => {
domain_string = constants.agg_sig_puzzle_additional_data;
domain_string = constants.puzzle();
coin.puzzle_hash.to_vec()
}
AggSigKind::Amount => {
domain_string = constants.agg_sig_amount_additional_data;
domain_string = constants.amount();
u64_to_bytes(coin.amount)
}
AggSigKind::PuzzleAmount => {
domain_string = constants.agg_sig_puzzle_amount_additional_data;
domain_string = constants.puzzle_amount();
let puzzle = coin.puzzle_hash;
[puzzle.to_vec(), u64_to_bytes(coin.amount)].concat()
}
AggSigKind::ParentAmount => {
domain_string = constants.agg_sig_parent_amount_additional_data;
domain_string = constants.parent_amount();
let parent = coin.parent_coin_info;
[parent.to_vec(), u64_to_bytes(coin.amount)].concat()
}
AggSigKind::ParentPuzzle => {
domain_string = constants.agg_sig_parent_puzzle_additional_data;
domain_string = constants.parent_puzzle();
[coin.parent_coin_info.to_vec(), coin.puzzle_hash.to_vec()].concat()
}
AggSigKind::Unsafe => {
Expand All @@ -59,7 +58,7 @@ impl RequiredSignature {
}
}
AggSigKind::Me => {
domain_string = constants.agg_sig_me_additional_data;
domain_string = constants.me();
coin.coin_id().to_vec()
}
};
Expand All @@ -78,7 +77,7 @@ impl RequiredSignature {
pub fn from_coin_spend(
allocator: &mut Allocator,
coin_spend: &CoinSpend,
constants: &ConsensusConstants,
constants: &AggSigConstants,
) -> Result<Vec<Self>, SignerError> {
let puzzle = coin_spend.puzzle_reveal.to_clvm(allocator)?;
let solution = coin_spend.solution.to_clvm(allocator)?;
Expand Down Expand Up @@ -108,7 +107,7 @@ impl RequiredSignature {
pub fn from_coin_spends(
allocator: &mut Allocator,
coin_spends: &[CoinSpend],
constants: &ConsensusConstants,
constants: &AggSigConstants,
) -> Result<Vec<Self>, SignerError> {
let mut required_signatures = Vec::new();
for coin_spend in coin_spends {
Expand Down Expand Up @@ -239,8 +238,10 @@ mod tests {
),
];

let constants = AggSigConstants::from(&*MAINNET_CONSTANTS);

for (condition, appended_info, domain_string) in cases {
let required = RequiredSignature::from_condition(&coin, condition, &MAINNET_CONSTANTS);
let required = RequiredSignature::from_condition(&coin, condition, &constants);

assert_eq!(required.public_key(), public_key);
assert_eq!(required.raw_message(), message.as_ref());
Expand Down
4 changes: 2 additions & 2 deletions crates/chia-sdk-test/src/peer_simulator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ mod tests {
to_program([AggSigMe::new(pk, b"Hello, world!".to_vec().into())])?,
)],
&[sk],
&sim.config.constants,
&(&sim.config.constants).into(),
)
.await;

Expand Down Expand Up @@ -331,7 +331,7 @@ mod tests {
])?,
)],
&[sk1, sk2],
&sim.config.constants,
&(&sim.config.constants).into(),
)
.await;

Expand Down
3 changes: 2 additions & 1 deletion crates/chia-sdk-test/src/simulator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ impl Simulator {
coin_spends: Vec<CoinSpend>,
secret_keys: &[SecretKey],
) -> Result<IndexMap<Bytes32, CoinState>, SimulatorError> {
let signature = sign_transaction(&coin_spends, secret_keys, &TESTNET11_CONSTANTS)?;
let signature =
sign_transaction(&coin_spends, secret_keys, &(&*TESTNET11_CONSTANTS).into())?;
self.new_transaction(
SpendBundle::new(coin_spends, signature),
&TESTNET11_CONSTANTS,
Expand Down
9 changes: 4 additions & 5 deletions crates/chia-sdk-test/src/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
use std::collections::HashMap;

use chia_bls::{sign, PublicKey, SecretKey, Signature};
use chia_consensus::consensus_constants::ConsensusConstants;
use chia_protocol::{CoinSpend, SpendBundle, TransactionAck};
use chia_sdk_client::Peer;
use chia_sdk_signer::RequiredSignature;
use chia_sdk_signer::{AggSigConstants, RequiredSignature};
use clvmr::Allocator;

use crate::SimulatorError;

pub fn sign_transaction(
coin_spends: &[CoinSpend],
secret_keys: &[SecretKey],
constants: &ConsensusConstants,
constants: &AggSigConstants,
) -> Result<Signature, SimulatorError> {
let mut allocator = Allocator::new();

Expand All @@ -39,7 +38,7 @@ pub async fn test_transaction_raw(
peer: &Peer,
coin_spends: Vec<CoinSpend>,
secret_keys: &[SecretKey],
constants: &ConsensusConstants,
constants: &AggSigConstants,
) -> anyhow::Result<TransactionAck> {
let aggregated_signature = sign_transaction(&coin_spends, secret_keys, constants)?;

Expand All @@ -56,7 +55,7 @@ pub async fn test_transaction(
peer: &Peer,
coin_spends: Vec<CoinSpend>,
secret_keys: &[SecretKey],
constants: &ConsensusConstants,
constants: &AggSigConstants,
) {
let ack = test_transaction_raw(peer, coin_spends, secret_keys, constants)
.await
Expand Down
Loading

0 comments on commit 1461c0e

Please sign in to comment.