Skip to content

Commit

Permalink
Merge pull request #36 from stakwork/velocity-control
Browse files Browse the repository at this point in the history
Velocity control
  • Loading branch information
Evanfeenstra authored Jul 30, 2023
2 parents ad9bc73 + bbadd1b commit 150f592
Show file tree
Hide file tree
Showing 14 changed files with 163 additions and 116 deletions.
34 changes: 34 additions & 0 deletions rmp-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ pub fn serialize_state_vec(
Ok(())
}

pub fn serialize_velocity(vel: &(u64, Vec<u64>)) -> Result<Vec<u8>> {
let mut buff = encode::buffer::ByteBuf::new();
encode::write_array_len(&mut buff, 2).map_err(Error::msg)?;
encode::write_u64(&mut buff, vel.0).map_err(Error::msg)?;
encode::write_array_len(&mut buff, vel.1.len() as u32).map_err(Error::msg)?;
for payment in vel.1.iter() {
encode::write_u64(&mut buff, *payment).map_err(Error::msg)?;
}
Ok(buff.into_vec())
}

pub fn deserialize_state_vec(
bytes: &mut decode::bytes::Bytes,
field_name: Option<&str>,
Expand All @@ -59,6 +70,21 @@ pub fn deserialize_state_vec(
Ok(object)
}

pub fn deserialize_velocity(b: &[u8]) -> Result<(u64, Vec<u64>)> {
let mut bytes = decode::bytes::Bytes::new(b);
let _ = decode::read_array_len(&mut bytes)
.map_err(|_| Error::msg("could not read array length"))?;
let bucket = decode::read_u64(&mut bytes).map_err(|_| Error::msg("could not read u64"))?;
let len = decode::read_array_len(&mut bytes)
.map_err(|_| Error::msg("could not read array length"))?;
let mut pmts: Vec<u64> = Vec::with_capacity(len as usize);
for _ in 0..len {
let x = decode::read_u64(&mut bytes).map_err(|_| Error::msg("could not read u64"))?;
pmts.push(x);
}
Ok((bucket, pmts))
}

pub fn serialize_state_map(map: &BTreeMap<String, (u64, Vec<u8>)>) -> Result<Vec<u8>> {
if TRACE {
log::info!("serialize_state_map: start");
Expand Down Expand Up @@ -212,3 +238,11 @@ fn state_map_serde() {
let object = deserialize_state_map(&bytes).unwrap();
assert_eq!(test, object);
}

#[test]
fn ser_velocity_test() {
let vel = (1, vec![123, 456, 789]);
let bytes = serialize_velocity(&vel).unwrap();
let vel2 = deserialize_velocity(&bytes).unwrap();
assert_eq!(vel, vel2);
}
35 changes: 23 additions & 12 deletions signer/src/mobile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ pub struct Args {
seed: [u8; 32],
network: Network,
policy: Policy,
velocity: Option<Velocity>,
allowlist: Vec<String>,
timestamp: u64, // number of seconds
lss_nonce: [u8; 32],
Expand All @@ -57,13 +56,14 @@ pub struct RunReturn {
pub lss_bytes: Option<Vec<u8>>,
pub sequence: u16,
pub cmd: String,
pub velocity: Option<Vec<u8>>,
pub velocity: Option<Velocity>,
}

pub fn run_init_1(
args: Args,
state: State,
lss_msg1: &[u8],
velocity: Option<Velocity>,
) -> Result<(
RunReturn,
RootHandlerBuilder,
Expand All @@ -73,7 +73,7 @@ pub fn run_init_1(
let init = Msg::from_slice(lss_msg1)?.into_init()?;
let server_pubkey = PublicKey::from_slice(&init.server_pubkey)?;
let nonce = args.lss_nonce.clone();
let (rhb, approver) = root_handler_builder(args, state)?;
let (rhb, approver) = root_handler_builder(args, state, velocity)?;
let (lss_signer, res1) = LssSigner::new(&rhb, &server_pubkey, Some(nonce));
Ok((
RunReturn::new_lss(topics::INIT_1_RES, res1, "LssInit".to_string()),
Expand All @@ -88,8 +88,9 @@ pub fn run_init_2(
state: State,
lss_msg1: &[u8],
lss_msg2: &[u8],
velocity: Option<Velocity>,
) -> Result<(RunReturn, RootHandler, Arc<SphinxApprover>, LssSigner)> {
let (_res1, rhb, approver, lss_signer) = run_init_1(args, state.clone(), lss_msg1)?;
let (_res1, rhb, approver, lss_signer) = run_init_1(args, state.clone(), lss_msg1, velocity)?;
let created = Msg::from_slice(&lss_msg2)?.into_created()?;
let (root_handler, res2) = lss_signer.build_with_lss(created, rhb, Some(state))?;
Ok((
Expand All @@ -107,16 +108,21 @@ pub fn run_vls(
lss_msg2: &[u8],
vls_msg: &[u8],
expected_sequence: Option<u16>,
velocity: Option<Velocity>,
) -> Result<RunReturn> {
let (_res, rh, _approver, lss_signer) = run_init_2(args, state, lss_msg1, lss_msg2)?;

let (_res, rh, approver, lss_signer) = run_init_2(args, state, lss_msg1, lss_msg2, velocity)?;
let s1 = approver.control().get_state();
let (vls_res, lss_res, sequence, cmd) =
handle_with_lss(&rh, &lss_signer, vls_msg.to_vec(), expected_sequence, true)?;
let ret = if lss_res.is_empty() {
let mut ret = if lss_res.is_empty() {
RunReturn::new_vls(topics::VLS_RES, vls_res, sequence, cmd)
} else {
RunReturn::new(topics::LSS_RES, vls_res, lss_res, sequence, cmd)
};
let s2 = approver.control().get_state();
if s1 != s2 {
ret.set_velocity(s2);
}
Ok(ret)
}

Expand All @@ -129,7 +135,7 @@ pub fn run_lss(
previous_vls: &[u8],
previous_lss: &[u8],
) -> Result<RunReturn> {
let (_res, _rh, _approver, lss_signer) = run_init_2(args, state, lss_msg1, lss_msg2)?;
let (_res, _rh, _approver, lss_signer) = run_init_2(args, state, lss_msg1, lss_msg2, None)?;

let prev = (previous_vls.to_vec(), previous_lss.to_vec());
let (topic, res) = handle_lss_msg(&lss_msg, Some(prev), &lss_signer)?;
Expand All @@ -144,6 +150,7 @@ pub fn run_lss(
fn root_handler_builder(
args: Args,
state: State,
velocity: Option<Velocity>,
) -> Result<(RootHandlerBuilder, Arc<SphinxApprover>)> {
use std::time::UNIX_EPOCH;

Expand All @@ -161,8 +168,8 @@ fn root_handler_builder(
args.seed,
args.network,
args.policy,
args.velocity,
args.allowlist,
velocity,
persister,
clock,
stf,
Expand Down Expand Up @@ -211,6 +218,9 @@ impl RunReturn {
velocity: None,
}
}
pub fn set_velocity(&mut self, velocity: Velocity) {
self.velocity = Some(velocity);
}
}

pub struct NowClock(Duration);
Expand Down Expand Up @@ -266,7 +276,6 @@ mod tests {
seed: [1; 32],
network: Network::Regtest,
policy: Default::default(),
velocity: None,
allowlist: vec![],
timestamp: ts.as_secs(),
lss_nonce: [32; 32],
Expand Down Expand Up @@ -338,7 +347,8 @@ mod tests {
})
.to_vec()?;

let (res1, _rhb, _approver, _lss_signer) = run_init_1(args.clone(), state.clone(), &bi1)?;
let (res1, _rhb, _approver, _lss_signer) =
run_init_1(args.clone(), state.clone(), &bi1, None)?;
let lss_bytes = res1.lss_bytes.unwrap();

let si1 = Response::from_slice(&lss_bytes)?.into_init()?;
Expand All @@ -348,7 +358,7 @@ mod tests {
let bi2 = lss_broker.get_created_state_msg(&si1).await?;

let (res2, _rh, _approver, _lss_signer) =
run_init_2(args.clone(), state.clone(), &bi1, &bi2)?;
run_init_2(args.clone(), state.clone(), &bi1, &bi2, None)?;
let lss_bytes2 = res2.lss_bytes.unwrap();

let si2 = Response::from_slice(&lss_bytes2)?.into_created()?;
Expand All @@ -367,6 +377,7 @@ mod tests {
&bi2,
&m,
Some(expected_sequence),
None,
)?;
expected_sequence = expected_sequence + 1;
println!("===> SEQ {:?}", rr.sequence);
Expand Down
6 changes: 3 additions & 3 deletions signer/src/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ pub fn builder(
seed: [u8; 32],
network: Network,
initial_policy: Policy,
initial_velocity: Option<Velocity>,
initial_allowlist: Vec<String>,
initial_velocity: Option<Velocity>,
persister: Arc<dyn Persist>,
) -> anyhow::Result<(RootHandlerBuilder, Arc<SphinxApprover>)> {
let clock = make_clock();
Expand All @@ -58,8 +58,8 @@ pub fn builder(
seed,
network,
initial_policy,
initial_velocity,
initial_allowlist,
initial_velocity,
persister,
clock,
random_time_factory,
Expand All @@ -86,8 +86,8 @@ pub fn builder_inner(
seed: [u8; 32],
network: Network,
initial_policy: Policy,
initial_velocity: Option<Velocity>,
initial_allowlist: Vec<String>,
initial_velocity: Option<Velocity>,
persister: Arc<dyn Persist>,
clock: Arc<dyn Clock>,
starting_time_factory: Arc<dyn StartingTimeFactory>,
Expand Down
1 change: 0 additions & 1 deletion sphinx-ffi/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ interface Args {
allowlist: string[]; // list of btc addresses
timestamp: number; // unix ts in seconds (10 digits)
lss_nonce: Bytes; // random 32 bytes
velocity?: Velocity; // optional
}

type State = { [k: string]: Bytes };
Expand Down
2 changes: 2 additions & 0 deletions sphinx-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ pub enum SphinxError {
BadArgs { r: String },
#[error("Bad State: {r}")]
BadState { r: String },
#[error("Bad Velocity: {r}")]
BadVelocity { r: String },
#[error("Init Failed: {r}")]
InitFailed { r: String },
#[error("LSS Failed: {r}")]
Expand Down
Loading

0 comments on commit 150f592

Please sign in to comment.