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

Merging in update_spend_tx. #391

Merged
merged 1 commit into from
May 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion doc/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ feerate.
### `updatespendtx`

The `updatespendtx` RPC Command stores or update the stored Spend transaction with the
given one.
given one. The signatures from both the old & the new transactions will be merged.

#### Request

Expand Down
36 changes: 29 additions & 7 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub enum CommandError {
/// (Got, Expected)
SpendNotEnoughSig(usize, usize),
SpendInvalidSig(Vec<u8>),
SpendSignaturesUpdate(revault_tx::error::InputSatisfactionError),
MissingCpfpKey,
ManagerOnly,
StakeholderOnly,
Expand Down Expand Up @@ -148,6 +149,9 @@ impl fmt::Display for CommandError {
}
Self::Race => write!(f, "Internal error due to a race. Please try again."),
Self::UnknownCancel(txid) => write!(f, "Unknown Cancel transaction: '{}'", txid),
Self::SpendSignaturesUpdate(error) => {
write!(f, "Error in updating the signature '{}'", error)
}
}
}
}
Expand Down Expand Up @@ -190,6 +194,7 @@ impl CommandError {
CommandError::Bitcoind(_) => ErrorCode::BITCOIND_ERROR,
CommandError::Tx(_) => ErrorCode::INTERNAL_ERROR,
CommandError::SpendFeerateTooLow(_, _) => ErrorCode::INVALID_PARAMS,
CommandError::SpendSignaturesUpdate(_) => ErrorCode::INVALID_PARAMS,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: you can use this syntax to avoid repetition:

CommandError::SpendFeerateTooLow(_, _) | CommandError::SpendSignaturesUpdate(_) => ErrorCode::INVALID_PARAMS,

Note: "nit" review comment are "Not Important Things". We use them to convey or discuss something, without it being an explicit request to the PR author to address it. In other words: feel free to address, or not.

// TODO: some of these probably need specific error codes
CommandError::SpendTooLarge
| CommandError::SpendUnknownUnVault(_)
Expand Down Expand Up @@ -1110,15 +1115,32 @@ impl DaemonControl {

db_unvaults.push(db_unvault);
}
let mut old_tx =
db_spend_transaction(&db_path, &spend_txid).expect("Database must be available");

if let Some(unwrapped_tx) = old_tx.as_mut() {
// Merging the signatures of `old_tx` into `spend_tx` and saving it.

let psbt_ins = spend_tx.into_psbt().inputs;

for (i, input) in psbt_ins.into_iter().enumerate() {
for (pubkey, raw_sig) in input.partial_sigs {
let sig = secp256k1::Signature::from_der(&raw_sig[..raw_sig.len() - 1])
.map_err(|_| CommandError::SpendInvalidSig(raw_sig.clone()))?;

// i remains in bound since the transaction is taken based on txid.
unwrapped_tx
.psbt
.add_signature(i, pubkey.key, sig, &revaultd.secp_ctx)
.map_err(|e| CommandError::SpendSignaturesUpdate(e))?;
}
}

// The user has the ability to set priority to the transaction in
// setspendtx, here we always set it to false.
if db_spend_transaction(&db_path, &spend_txid)
.expect("Database must be available")
.is_some()
{
log::debug!("Updating Spend transaction '{}'", spend_txid);
db_update_spend(&db_path, &spend_tx, false).expect("Database must be available");
// The user has the ability to set priority to the transaction in
// setspendtx, here we always set it to false.
db_update_spend(&db_path, &unwrapped_tx.psbt, false)
.expect("Database must be available");
} else {
log::debug!("Storing new Spend transaction '{}'", spend_txid);
db_insert_spend(&db_path, &db_unvaults, &spend_tx).expect("Database must be available");
Expand Down
55 changes: 55 additions & 0 deletions tests/test_spend.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,61 @@
)


@pytest.mark.skipif(not POSTGRES_IS_SETUP, reason="Needs Postgres for servers db")
def test_update_spend_tx(revault_network, bitcoind):
CSV = 12
revault_network.deploy(
n_stakeholders=2, n_managers=3, managers_threshold=3, csv=CSV
)
managers = [revault_network.man(i) for i in range(3)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: you can just use the mans method :)

def mans(self):
return self.stkman_wallets + self.man_wallets
def stks(self):
return self.stkman_wallets + self.stk_wallets
def participants(self):
return self.stkman_wallets + self.stk_wallets + self.man_wallets
def man(self, n):
"""Get the {n}th manager (including the stakeholder-managers first)"""
mans = self.stkman_wallets + self.man_wallets
return mans[n]

amount = 0.24
vault = revault_network.fund(amount)
deposit = f"{vault['txid']}:{vault['vout']}"
derivation_indices = [vault["derivation_index"]]

addr = bitcoind.rpc.getnewaddress()
spent_vaults = [deposit]
feerate = 2
fees = revault_network.compute_spendtx_fees(feerate, len(spent_vaults), 1)
destination = {addr: vault["amount"] - fees}

revault_network.secure_vault(vault)
revault_network.activate_vault(vault)

spend_tx = managers[0].rpc.getspendtx(spent_vaults, destination, feerate)[
"spend_tx"
]["psbt"]
spend_tx_a = spend_tx
spend_tx_b = spend_tx

# Transaction with only the first signature
spend_tx_a = managers[0].man_keychain.sign_spend_psbt(
spend_tx_a, derivation_indices
)

# Transaction with other 2 signatures.
for man in managers[1:]:
spend_tx_b = man.man_keychain.sign_spend_psbt(spend_tx_b, derivation_indices)

# Storing the transaction with first signature.
managers[0].rpc.updatespendtx(spend_tx_a)
managers[0].wait_for_log("Storing new Spend transaction")

# Updating the transaction with the last 2 signatures.
managers[0].rpc.updatespendtx(spend_tx_b)
managers[0].wait_for_log("Updating Spend transaction")

spend_txs = managers[0].rpc.listspendtxs()["spend_txs"]
assert len(spend_txs) == 1

serialized_psbt = spend_txs[0]["psbt"]
psbt = serializations.PSBT()
psbt.deserialize(serialized_psbt)

# Must have 3 signatures if they are merged.
assert len(psbt.inputs[0].partial_sigs) == 3


@pytest.mark.skipif(not POSTGRES_IS_SETUP, reason="Needs Postgres for servers db")
def test_spendtx_management(revault_network, bitcoind):
CSV = 12
Expand Down