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

Introduce mintscript::SigntureOnlyChecker and use it in the wallet #1791

Merged
merged 9 commits into from
Jul 19, 2024
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
1 change: 1 addition & 0 deletions chainstate/src/detail/ban_score.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ impl BanScore for tx_verifier::error::TimelockContextError {
fn ban_score(&self) -> u32 {
match self {
Self::TimelockedAccount => 0,
Self::MissingUtxoSource => 0,
Self::HeaderLoad(e, _) => e.ban_score(),
}
}
Expand Down
1 change: 1 addition & 0 deletions chainstate/src/detail/error_classification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ impl BlockProcessingErrorClassification for tx_verifier::error::TimelockContextE
fn classify(&self) -> BlockProcessingErrorClass {
match self {
Self::TimelockedAccount => BlockProcessingErrorClass::General,
Self::MissingUtxoSource => BlockProcessingErrorClass::General,
Self::HeaderLoad(e, _) => e.classify(),
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ use common::{
chain::{
block::timestamp::BlockTimestamp,
signature::{inputsig::InputWitness, DestinationSigError, Transactable},
ChainConfig, GenBlock, TxInput, TxOutput,
tokens::TokenId,
ChainConfig, DelegationId, Destination, GenBlock, PoolId, TxInput, TxOutput,
},
primitives::{BlockHeight, Id},
};
Expand All @@ -33,6 +34,8 @@ use crate::TransactionVerifierStorageRef;

use super::TransactionSourceForConnect;

pub mod signature_only_check;

pub type HashlockError = mintscript::checker::HashlockError;
pub type TimelockError = mintscript::checker::TimelockError<TimelockContextError>;
pub type ScriptError =
Expand Down Expand Up @@ -61,6 +64,22 @@ impl From<mintscript::script::ScriptError<Infallible, TimelockError, Infallible>
}
}

impl From<mintscript::script::ScriptError<DestinationSigError, Infallible, Infallible>>
for InputCheckErrorPayload
{
fn from(
value: mintscript::script::ScriptError<DestinationSigError, Infallible, Infallible>,
) -> Self {
let err = match value {
mintscript::script::ScriptError::Signature(e) => ScriptError::Signature(e),
mintscript::script::ScriptError::Timelock(_e) => unreachable!(),
mintscript::script::ScriptError::Hashlock(e) => ScriptError::Hashlock(e.into()),
mintscript::script::ScriptError::Threshold(e) => ScriptError::Threshold(e),
};
Self::Verification(err)
}
}

#[derive(PartialEq, Eq, Clone, thiserror::Error, Debug)]
#[error("Error verifying input #{input_num}: {error}")]
pub struct InputCheckError {
Expand All @@ -84,6 +103,9 @@ pub enum TimelockContextError {
#[error("Timelocks on accounts not supported")]
TimelockedAccount,

#[error("Utxo source is missing")]
MissingUtxoSource,

#[error("Loading ancestor header at height {1} failed: {0}")]
HeaderLoad(chainstate_types::GetAncestorError, BlockHeight),
}
Expand Down Expand Up @@ -113,7 +135,11 @@ impl<'a> PerInputData<'a> {
let err = InputCheckErrorPayload::MissingUtxo(outpoint.clone());
InputCheckError::new(input_num, err)
})?;
InputInfo::Utxo { outpoint, utxo }
InputInfo::Utxo {
outpoint,
utxo_source: Some(utxo.source().clone()),
utxo: utxo.take_output(),
}
}
TxInput::Account(outpoint) => InputInfo::Account { outpoint },
TxInput::AccountCommand(_, command) => InputInfo::AccountCommand { command },
Expand Down Expand Up @@ -177,20 +203,45 @@ where
TV: tokens_accounting::TokensAccountingView<Error = tokens_accounting::Error>,
OV: orders_accounting::OrdersAccountingView<Error = orders_accounting::Error>,
{
type PoSAccounting = AV;
type Tokens = TV;
type Orders = OV;

fn pos_accounting(&self) -> &Self::PoSAccounting {
&self.pos_accounting
}

fn tokens(&self) -> &Self::Tokens {
&self.tokens_accounting
fn get_pool_decommission_destination(
&self,
pool_id: &PoolId,
) -> Result<Option<Destination>, pos_accounting::Error> {
Ok(self
.pos_accounting
.get_pool_data(*pool_id)?
.map(|pool| pool.decommission_destination().clone()))
}

fn get_delegation_spend_destination(
&self,
delegation_id: &DelegationId,
) -> Result<Option<Destination>, pos_accounting::Error> {
Ok(self
.pos_accounting
.get_delegation_data(*delegation_id)?
.map(|delegation| delegation.spend_destination().clone()))
}

fn get_tokens_authority(
&self,
token_id: &TokenId,
) -> Result<Option<Destination>, tokens_accounting::Error> {
Ok(
self.tokens_accounting.get_token_data(token_id)?.map(|token| match token {
tokens_accounting::TokenData::FungibleToken(data) => data.authority().clone(),
}),
)
}

fn orders(&self) -> &Self::Orders {
&self.orders_accounting
fn get_orders_conclude_destination(
&self,
order_id: &common::chain::OrderId,
) -> Result<Option<Destination>, orders_accounting::Error> {
Ok(self
.orders_accounting
.get_order_data(order_id)?
.map(|data| data.conclude_key().clone()))
}
}

Expand Down Expand Up @@ -341,7 +392,11 @@ impl<S: TransactionVerifierStorageRef> TimelockContext for InputVerifyContextTim

fn source_height(&self) -> Result<BlockHeight, Self::Error> {
match self.info() {
InputInfo::Utxo { outpoint: _, utxo } => match utxo.source() {
InputInfo::Utxo {
outpoint: _,
utxo: _,
utxo_source,
} => match utxo_source.as_ref().ok_or(TimelockContextError::MissingUtxoSource)? {
utxo::UtxoSource::Blockchain(height) => Ok(*height),
utxo::UtxoSource::Mempool => Ok(self.ctx.spending_height),
},
Expand All @@ -353,7 +408,11 @@ impl<S: TransactionVerifierStorageRef> TimelockContext for InputVerifyContextTim

fn source_time(&self) -> Result<BlockTimestamp, Self::Error> {
match self.info() {
InputInfo::Utxo { outpoint: _, utxo } => match utxo.source() {
InputInfo::Utxo {
outpoint: _,
utxo: _,
utxo_source,
} => match utxo_source.as_ref().ok_or(TimelockContextError::MissingUtxoSource)? {
utxo::UtxoSource::Blockchain(height) => {
let block_index_getter = |db_tx: &S, _: &ChainConfig, id: &Id<GenBlock>| {
db_tx.get_gen_block_index(id)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Copyright (c) 2024 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::convert::Infallible;

use common::chain::{
partially_signed_transaction::PartiallySignedTransaction,
signature::{inputsig::InputWitness, DestinationSigError, Transactable},
tokens::TokenId,
ChainConfig, DelegationId, Destination, PoolId, SignedTransaction, TxInput, TxOutput,
};
use mintscript::{
script::ScriptError, translate::InputInfoProvider, InputInfo, SignatureContext, TranslateInput,
};
use utils::ensure;

use super::{InputCheckError, InputCheckErrorPayload, PerInputData};

struct InputVerifyContextSignature<'a, T> {
Copy link
Contributor

Choose a reason for hiding this comment

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

This is a very confusing name

Copy link
Member Author

Choose a reason for hiding this comment

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

this is just a name in line with others like InputVerifyContextTimelock

chain_config: &'a ChainConfig,
tx: &'a T,
outpoint_destination: &'a Destination,
inputs_utxos: &'a [Option<&'a TxOutput>],
input_num: usize,
input_data: PerInputData<'a>,
}

impl<T: Transactable> SignatureContext for InputVerifyContextSignature<'_, T> {
type Tx = T;

fn chain_config(&self) -> &ChainConfig {
self.chain_config
}

fn transaction(&self) -> &Self::Tx {
self.tx
}

fn input_utxos(&self) -> &[Option<&TxOutput>] {
self.inputs_utxos
}

fn input_num(&self) -> usize {
self.input_num
}
}

impl<T: Transactable> mintscript::translate::SignatureInfoProvider
for InputVerifyContextSignature<'_, T>
{
fn get_pool_decommission_destination(
&self,
_pool_id: &PoolId,
) -> Result<Option<Destination>, pos_accounting::Error> {
Ok(Some(self.outpoint_destination.clone()))
}

fn get_delegation_spend_destination(
&self,
_delegation_id: &DelegationId,
) -> Result<Option<Destination>, pos_accounting::Error> {
Ok(Some(self.outpoint_destination.clone()))
}

fn get_tokens_authority(
&self,
_token_id: &TokenId,
) -> Result<Option<Destination>, tokens_accounting::Error> {
Ok(Some(self.outpoint_destination.clone()))
}

fn get_orders_conclude_destination(
&self,
_order_id: &common::chain::OrderId,
) -> Result<Option<Destination>, orders_accounting::Error> {
Ok(Some(self.outpoint_destination.clone()))
}
}

impl<T: Transactable> InputInfoProvider for InputVerifyContextSignature<'_, T> {
fn input_info(&self) -> &InputInfo {
self.input_data.input_info()
}

fn witness(&self) -> &InputWitness {
self.input_data.witness()
}
}

// Prevent BlockRewardTransactable from being used here
pub trait SignatureOnlyVerifiable {}
impl SignatureOnlyVerifiable for SignedTransaction {}
impl SignatureOnlyVerifiable for PartiallySignedTransaction {}

pub fn verify_tx_signature<T: Transactable + SignatureOnlyVerifiable>(
chain_config: &ChainConfig,
outpoint_destination: &Destination,
tx: &T,
inputs_utxos: &[Option<&TxOutput>],
input_num: usize,
) -> Result<(), InputCheckError> {
let map_sig_err = |e: DestinationSigError| {
InputCheckError::new(
input_num,
ScriptError::<DestinationSigError, Infallible, Infallible>::Signature(e),
)
};

let inputs = tx
.inputs()
.ok_or(DestinationSigError::SignatureVerificationWithoutInputs)
.map_err(map_sig_err)?;
let input = inputs
.get(input_num)
.ok_or(DestinationSigError::InvalidInputIndex(
input_num,
inputs.len(),
))
.map_err(map_sig_err)?;

ensure!(
inputs.len() == inputs_utxos.len(),
map_sig_err(DestinationSigError::InvalidUtxoCountVsInputs(
inputs_utxos.len(),
inputs.len()
))
);

let input_info = match input {
TxInput::Utxo(outpoint) => {
let utxo = inputs_utxos[input_num]
.ok_or(InputCheckError::new(
input_num,
InputCheckErrorPayload::MissingUtxo(outpoint.clone()),
))?
.clone();
InputInfo::Utxo {
outpoint,
utxo,
utxo_source: None,
}
}
TxInput::Account(outpoint) => InputInfo::Account { outpoint },
TxInput::AccountCommand(_, command) => InputInfo::AccountCommand { command },
};
let input_witness = tx.signatures()[input_num]
.clone()
.ok_or(DestinationSigError::SignatureNotFound)
.map_err(map_sig_err)?;

let input_data = PerInputData::new(input_info, input_witness);
let context = InputVerifyContextSignature {
chain_config,
tx,
outpoint_destination,
inputs_utxos,
input_num,
input_data,
};
let script = mintscript::translate::SignatureOnlyTx::translate_input(&context)
.map_err(|e| InputCheckError::new(input_num, e))?;
let mut checker = mintscript::ScriptChecker::signature_only(context);
script.verify(&mut checker).map_err(|e| InputCheckError::new(input_num, e))?;

Ok(())
}
4 changes: 4 additions & 0 deletions common/src/chain/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use partially_signed_transaction::PartiallySignedTransaction;
use thiserror::Error;

use serialization::{DirectDecode, DirectEncode};
Expand All @@ -33,6 +34,7 @@ pub use account_nonce::*;
pub mod utxo_outpoint;
pub use utxo_outpoint::*;

pub mod partially_signed_transaction;
pub mod signed_transaction;

pub mod output;
Expand Down Expand Up @@ -100,6 +102,8 @@ impl Eq for WithId<Transaction> {}
pub enum TransactionCreationError {
#[error("The number of signatures does not match the number of inputs")]
InvalidWitnessCount,
#[error("Failed to convert partially signed tx to signed")]
FailedToConvertPartiallySignedTx(PartiallySignedTransaction),
}

impl Transaction {
Expand Down
Loading
Loading