diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/.lock b/static/rust/redstone/crypto_secp256k1,network_casper/.lock deleted file mode 100755 index e69de29b..00000000 diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/crates.js b/static/rust/redstone/crypto_secp256k1,network_casper/crates.js deleted file mode 100644 index 6d4f9bdc..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/crates.js +++ /dev/null @@ -1 +0,0 @@ -window.ALL_CRATES = ["redstone"]; \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/.lock b/static/rust/redstone/crypto_secp256k1,network_casper/doc/.lock deleted file mode 100755 index e69de29b..00000000 diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/crates.js b/static/rust/redstone/crypto_secp256k1,network_casper/doc/crates.js deleted file mode 100644 index 6d4f9bdc..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/doc/crates.js +++ /dev/null @@ -1 +0,0 @@ -window.ALL_CRATES = ["redstone"]; \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/help.html b/static/rust/redstone/crypto_secp256k1,network_casper/doc/help.html deleted file mode 100644 index f173d86a..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/doc/help.html +++ /dev/null @@ -1 +0,0 @@ -
pub(crate) fn aggregate_values(
- config: Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<U256>
Aggregates values from a collection of data packages according to the provided configuration.
-This function takes a configuration and a vector of data packages, constructs a matrix of values
-and their corresponding signers, and then aggregates these values based on the aggregation logic
-defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-an average of the values, selecting the median, or applying a custom algorithm defined within the
-aggregate_matrix
function.
The primary purpose of this function is to consolidate data from multiple sources into a coherent
-and singular value set that adheres to the criteria specified in the Config
.
config
- A Config
instance containing settings and parameters used to guide the aggregation process.data_packages
- A vector of DataPackage
instances, each representing a set of values and associated
-metadata collected from various sources or signers.Returns a Vec<U256>
, which is a vector of aggregated values resulting from applying the aggregation
-logic to the input data packages as per the specified configuration. Each U256
value in the vector
-represents an aggregated result derived from the corresponding data packages.
This function is internal to the crate (pub(crate)
) and not exposed as part of the public API. It is
-designed to be used by other components within the same crate that require value aggregation functionality.
fn make_value_signer_matrix(
- config: &Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<Vec<Option<U256>>>
pub struct Config {
- pub signer_count_threshold: u8,
- pub signers: Vec<Bytes>,
- pub feed_ids: Vec<U256>,
- pub block_timestamp: u64,
-}
Configuration for a RedStone payload processor.
-Specifies the parameters necessary for the verification and aggregation of values -from various data points passed by the RedStone payload.
-signer_count_threshold: u8
The minimum number of signers required validating the data.
-Specifies how many unique signers (from different addresses) are required -for the data to be considered valid and trustworthy.
-signers: Vec<Bytes>
List of identifiers for signers authorized to sign the data.
-Each signer is identified by a unique, network-specific byte string (Bytes
),
-which represents their address.
feed_ids: Vec<U256>
Identifiers for the data feeds from which values are aggregated.
-Each data feed id is represented by the network-specific U256
type.
block_timestamp: u64
The current block time in timestamp format, used for verifying data timeliness.
-The value’s been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows -for determining whether the data is current in the context of blockchain time.
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult
pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult
The main processor of the RedStone payload.
-config
- Configuration of the payload processing.payload_bytes
- Network-specific byte-list of the payload to be processed.pub struct ProcessorResult {
- pub min_timestamp: u64,
- pub values: Vec<U256>,
-}
Represents the result of processing the RedStone payload.
-This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-particularly focusing on time-sensitive data and its associated values, according to the Config
.
min_timestamp: u64
The minimum timestamp encountered during processing.
-This field captures the earliest time point (in milliseconds since the Unix epoch) -among the processed data packages, indicating the starting boundary of the dataset’s time range.
-values: Vec<U256>
A collection of values processed during the operation.
-Each element in this vector represents a processed value corresponding
-to the passed data_feed item in the Config
.
self
and other
values to be equal, and is used
-by ==
.pub(crate) trait Validator {
- // Required methods
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
- fn validate_signer_count_threshold(
- &self,
- index: usize,
- values: &[Option<U256>],
- ) -> Vec<U256>;
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
A trait defining validation operations for data feeds and signers.
-This trait specifies methods for validating aspects of data feeds and signers within a system that -requires data integrity and authenticity checks. Implementations of this trait are responsible for -defining the logic behind each validation step, ensuring that data conforms to expected rules and -conditions.
-Retrieves the index of a given data feed.
-This method takes a feed_id
representing the unique identifier of a data feed and
-returns an Option<usize>
indicating the index of the feed within a collection of feeds.
-If the feed does not exist, None
is returned.
feed_id
: U256
- The unique identifier of the data feed.Option<usize>
- The index of the feed if it exists, or None
if it does not.Retrieves the index of a given signer.
-This method accepts a signer identifier in the form of a byte slice and returns an
-Option<usize>
indicating the signer’s index within a collection of signers. If the signer
-is not found, None
is returned.
signer
: &[u8]
- A byte slice representing the signer’s identifier.Option<usize>
- The index of the signer if found, or None
if not found.Validates the signer count threshold for a given index within a set of values.
-This method is responsible for ensuring that the number of valid signers meets or exceeds
-a specified threshold necessary for a set of data values to be considered valid. It returns
-a vector of U256
if the values pass the validation, to be processed in other steps.
index
: usize
- The index of the data value being validated.values
: &[Option<U256>]
- A slice of optional U256
values associated with the data.Vec<U256>
- A vector of U256
values that meet the validation criteria.Validates the timestamp for a given index.
-This method checks whether a timestamp associated with a data value at a given index -meets specific conditions (e.g., being within an acceptable time range). It returns -the validated timestamp if it’s valid, to be processed in other steps.
-index
: usize
- The index of the data value whose timestamp is being validated.timestamp
: u64
- The timestamp to be validated.u64
- The validated timestamp.redstone
is a collection of utilities to make deserializing&decrypting RedStone payload.
-It contains a pure Rust implementation and also an extension for some networks.
Different crypto-mechanisms are easily injectable.
-The current implementation contains secp256k1
- and k256
-based variants.
Redirecting to macro.print_and_panic.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_and_panic.html b/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_and_panic.html deleted file mode 100644 index b308eb68..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_and_panic.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_and_panic { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
Redirecting to macro.print_debug.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_debug.html b/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_debug.html deleted file mode 100644 index 3cb863d6..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/doc/redstone/macro.print_debug.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_debug { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
pub trait AsAsciiStr {
- // Required method
- fn as_ascii_str(&self) -> String;
-}
pub trait AsHexStr {
- // Required method
- fn as_hex_str(&self) -> String;
-}
pub trait Assert<F> {
- // Required method
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
pub trait Unwrap<R> {
- type ErrorArg;
-
- // Required method
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
pub struct Casper;
pub enum Error {
- ContractError(Box<dyn ContractErrorContent>),
- NumberOverflow(U256),
- ArrayIsEmpty,
- CryptographicError(usize),
- SizeNotSupported(usize),
- WrongRedStoneMarker(Vec<u8>),
- NonEmptyPayloadRemainder(Vec<u8>),
- InsufficientSignerCount(usize, usize, U256),
- TimestampTooOld(usize, u64),
- TimestampTooFuture(usize, u64),
- ClonedContractError(u8, String),
-}
Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-These errors include issues with contract logic, data types, -cryptographic operations, and conditions specific to the requirements.
-Represents errors that arise from the contract itself.
-This variant is used for encapsulating errors that are specific to the contract’s logic -or execution conditions that aren’t covered by more specific error types.
-Indicates an overflow error with U256
numbers.
Used when operations on U256
numbers exceed their maximum value, potentially leading
-to incorrect calculations or state.
Used when an expected non-empty array or vector is found to be empty.
-This could occur in scenarios where the contract logic requires a non-empty collection -of items for the correct operation, for example, during aggregating the values.
-Represents errors related to cryptographic operations.
-This includes failures in signature verification, hashing, or other cryptographic -processes, with the usize indicating the position or identifier of the failed operation.
-Signifies that an unsupported size was encountered.
-This could be used when a data structure or input does not meet the expected size -requirements for processing.
-Indicates that the marker bytes for RedStone are incorrect.
-This error is specific to scenarios where marker or identifier bytes do not match -expected values, potentially indicating corrupted or tampered data.
-Used when there is leftover data in a payload that should have been empty.
-This could indicate an error in data parsing or that additional, unexpected data -was included in a message or transaction.
-Indicates that the number of signers does not meet the required threshold.
-This variant includes the current number of signers, the required threshold, and -potentially a feed_id related to the operation that failed due to insufficient signers.
-Used when a timestamp is older than allowed by the processor logic.
-Includes the position or identifier of the timestamp and the threshold value, -indicating that the provided timestamp is too far in the past.
-Indicates that a timestamp is further in the future than allowed.
-Similar to TimestampTooOld
, but for future timestamps exceeding the contract’s
-acceptance window.
Represents errors that need to clone ContractErrorContent
, which is not supported by default.
This variant allows for the manual duplication of contract error information, including -an error code and a descriptive message.
-pub trait FromBytesRepr<T> {
- // Required method
- fn from_bytes_repr(bytes: T) -> Self;
-}
pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- // Required methods
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage
pub(crate) fn trim_data_packages(
- payload: &mut Vec<u8>,
- count: usize,
-) -> Vec<DataPackage>
pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
signer_address: Vec<u8>
§timestamp: u64
§data_points: Vec<DataPoint>
source
. Read moreself
and other
values to be equal, and is used
-by ==
.fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint
pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
feed_id: U256
§value: U256
pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
data_packages: Vec<DataPackage>
pub(crate) trait FilterSome<Output> {
- // Required method
- fn filter_some(&self) -> Output;
-}
fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>where
- T: PartialOrd,
trait Averageable: Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy { }
pub trait TrimZeros {
- // Required method
- fn trim_zeros(self) -> Self;
-}
U::from(self)
.\nThe minimum number of signers required validating the data.\nList of identifiers for signers authorized to sign the …\nThe main processor of the RedStone payload.\nRepresents the result of processing the RedStone payload.\nReturns the argument unchanged.\nCalls U::from(self)
.\nThe minimum timestamp encountered during processing.\nA collection of values processed during the operation.\nA trait defining validation operations for data feeds and …\nRetrieves the index of a given data feed.\nRetrieves the index of a given signer.\nValidates the signer count threshold for a given index …\nValidates the timestamp for a given index.\nReturns the argument unchanged.\nCalls U::from(self)
.\nUsed when an expected non-empty array or vector is found …\nRepresents errors that need to clone ContractErrorContent
, …\nRepresents errors that arise from the contract itself.\nRepresents errors related to cryptographic operations.\nErrors that can be encountered in the …\nIndicates that the number of signers does not meet the …\nUsed when there is leftover data in a payload that should …\nIndicates an overflow error with U256
numbers.\nSignifies that an unsupported size was encountered.\nIndicates that a timestamp is further in the future than …\nUsed when a timestamp is older than allowed by the …\nIndicates that the marker bytes for RedStone are incorrect.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.")
\ No newline at end of file
diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/doc/settings.html b/static/rust/redstone/crypto_secp256k1,network_casper/doc/settings.html
deleted file mode 100644
index 9631dcb2..00000000
--- a/static/rust/redstone/crypto_secp256k1,network_casper/doc/settings.html
+++ /dev/null
@@ -1 +0,0 @@
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -
use crate::{
- core::{config::Config, validator::Validator},
- network::specific::U256,
- print_debug,
- protocol::data_package::DataPackage,
- utils::median::Median,
-};
-
-type Matrix = Vec<Vec<Option<U256>>>;
-
-/// Aggregates values from a collection of data packages according to the provided configuration.
-///
-/// This function takes a configuration and a vector of data packages, constructs a matrix of values
-/// and their corresponding signers, and then aggregates these values based on the aggregation logic
-/// defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-/// an average of the values, selecting the median, or applying a custom algorithm defined within the
-/// `aggregate_matrix` function.
-///
-/// The primary purpose of this function is to consolidate data from multiple sources into a coherent
-/// and singular value set that adheres to the criteria specified in the `Config`.
-///
-/// # Arguments
-///
-/// * `config` - A `Config` instance containing settings and parameters used to guide the aggregation process.
-/// * `data_packages` - A vector of `DataPackage` instances, each representing a set of values and associated
-/// metadata collected from various sources or signers.
-///
-/// # Returns
-///
-/// Returns a `Vec<U256>`, which is a vector of aggregated values resulting from applying the aggregation
-/// logic to the input data packages as per the specified configuration. Each `U256` value in the vector
-/// represents an aggregated result derived from the corresponding data packages.
-///
-/// # Note
-///
-/// This function is internal to the crate (`pub(crate)`) and not exposed as part of the public API. It is
-/// designed to be used by other components within the same crate that require value aggregation functionality.
-pub(crate) fn aggregate_values(config: Config, data_packages: Vec<DataPackage>) -> Vec<U256> {
- aggregate_matrix(make_value_signer_matrix(&config, data_packages), config)
-}
-
-fn aggregate_matrix(matrix: Matrix, config: Config) -> Vec<U256> {
- matrix
- .iter()
- .enumerate()
- .map(|(index, values)| {
- config
- .validate_signer_count_threshold(index, values)
- .median()
- })
- .collect()
-}
-
-fn make_value_signer_matrix(config: &Config, data_packages: Vec<DataPackage>) -> Matrix {
- let mut matrix = vec![vec![None; config.signers.len()]; config.feed_ids.len()];
-
- data_packages.iter().for_each(|data_package| {
- if let Some(signer_index) = config.signer_index(&data_package.signer_address) {
- data_package.data_points.iter().for_each(|data_point| {
- if let Some(feed_index) = config.feed_index(data_point.feed_id) {
- matrix[feed_index][signer_index] = data_point.value.into()
- }
- })
- }
- });
-
- print_debug!("{:?}", matrix);
-
- matrix
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod aggregate_matrix_tests {
- use crate::{
- core::{aggregator::aggregate_matrix, config::Config},
- helpers::iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- };
-
- #[test]
- fn test_aggregate_matrix() {
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8, 23].iter_into_opt(),
- ];
-
- for signer_count_threshold in 0..Config::test().signers.len() + 1 {
- let mut config = Config::test();
- config.signer_count_threshold = signer_count_threshold as u8;
-
- let result = aggregate_matrix(matrix.clone(), config);
-
- assert_eq!(result, vec![12u8, 22].iter_into());
- }
- }
-
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_one_value() {
- let mut config = Config::test();
- config.signer_count_threshold = 1;
-
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8.into(), None].opt_iter_into_opt(),
- ];
-
- let result = aggregate_matrix(matrix, config);
-
- assert_eq!(result, vec![12u8, 21].iter_into());
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_whole_feed() {
- let mut config = Config::test();
- config.signer_count_threshold = 0;
-
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, config);
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #0 (ETH)")]
- #[test]
- fn test_aggregate_matrix_missing_one_value() {
- let matrix = vec![
- vec![21u8.into(), None].opt_iter_into_opt(),
- vec![11u8, 12].iter_into_opt(),
- ];
-
- aggregate_matrix(matrix, Config::test());
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #1 (BTC)")]
- #[test]
- fn test_aggregate_matrix_missing_whole_feed() {
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, Config::test());
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod make_value_signer_matrix {
- use crate::{
- core::{
- aggregator::{make_value_signer_matrix, Matrix},
- config::Config,
- test_helpers::{AVAX, BTC, ETH, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2},
- },
- helpers::iter_into::IterInto,
- network::specific::U256,
- protocol::data_package::DataPackage,
- };
-
- #[test]
- fn test_make_value_signer_matrix_empty() {
- let config = Config::test();
-
- test_make_value_signer_matrix_of(
- vec![],
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_exact() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_greater() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_smaller() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_diagonal() {
- let data_packages = vec![
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11.into(), None], vec![None, 22.into()]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_repetitions() {
- let data_packages = vec![
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 202, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 101, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![101, 12].iter_into(), vec![21, 202].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_all_wrong() {
- let config = Config::test();
-
- let data_packages = vec![
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_mix() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- fn test_make_value_signer_matrix_of(
- data_packages: Vec<DataPackage>,
- expected_values: Vec<Vec<Option<u128>>>,
- ) {
- let config = &Config::test();
- let result = make_value_signer_matrix(config, data_packages);
-
- let expected_matrix: Matrix = expected_values
- .iter()
- .map(|row| {
- (row.iter()
- .map(|&value| value.map(U256::from))
- .collect::<Vec<_>>())
- .iter_into() as Vec<Option<U256>>
- })
- .collect();
-
- assert_eq!(result, expected_matrix)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -
use crate::network::specific::{Bytes, U256};
-
-/// Configuration for a RedStone payload processor.
-///
-/// Specifies the parameters necessary for the verification and aggregation of values
-/// from various data points passed by the RedStone payload.
-#[derive(Debug)]
-pub struct Config {
- /// The minimum number of signers required validating the data.
- ///
- /// Specifies how many unique signers (from different addresses) are required
- /// for the data to be considered valid and trustworthy.
- pub signer_count_threshold: u8,
-
- /// List of identifiers for signers authorized to sign the data.
- ///
- /// Each signer is identified by a unique, network-specific byte string (`Bytes`),
- /// which represents their address.
- pub signers: Vec<Bytes>,
-
- /// Identifiers for the data feeds from which values are aggregated.
- ///
- /// Each data feed id is represented by the network-specific `U256` type.
- pub feed_ids: Vec<U256>,
-
- /// The current block time in timestamp format, used for verifying data timeliness.
- ///
- /// The value's been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows
- /// for determining whether the data is current in the context of blockchain time.
- pub block_timestamp: u64,
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -
use crate::{
- core::{
- aggregator::aggregate_values, config::Config, processor_result::ProcessorResult,
- validator::Validator,
- },
- network::specific::Bytes,
- print_debug,
- protocol::payload::Payload,
-};
-
-/// The main processor of the RedStone payload.
-///
-///
-/// # Arguments
-///
-/// * `config` - Configuration of the payload processing.
-/// * `payload_bytes` - Network-specific byte-list of the payload to be processed.
-pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult {
- #[allow(clippy::useless_conversion)]
- let mut bytes: Vec<u8> = payload_bytes.into();
- let payload = Payload::make(&mut bytes);
- print_debug!("{:?}", payload);
-
- make_processor_result(config, payload)
-}
-
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult {
- let min_timestamp = payload
- .data_packages
- .iter()
- .enumerate()
- .map(|(index, dp)| config.validate_timestamp(index, dp.timestamp))
- .min()
- .unwrap();
-
- let values = aggregate_values(config, payload.data_packages);
-
- print_debug!("{} {:?}", min_timestamp, values);
-
- ProcessorResult {
- values,
- min_timestamp,
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- processor::make_processor_result,
- processor_result::ProcessorResult,
- test_helpers::{
- BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- },
- helpers::iter_into::IterInto,
- protocol::{data_package::DataPackage, payload::Payload},
- };
-
- #[test]
- fn test_make_processor_result() {
- let data_packages = vec![
- DataPackage::test(
- ETH,
- 11,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 5).into(),
- ),
- DataPackage::test(
- ETH,
- 13,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP + 3).into(),
- ),
- DataPackage::test(
- BTC,
- 32,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP - 2).into(),
- ),
- DataPackage::test(
- BTC,
- 31,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 400).into(),
- ),
- ];
-
- let result = make_processor_result(Config::test(), Payload { data_packages });
-
- assert_eq!(
- result,
- ProcessorResult {
- min_timestamp: TEST_BLOCK_TIMESTAMP - 2,
- values: vec![12u8, 31].iter_into()
- }
- );
- }
-}
-
use crate::network::specific::U256;
-
-/// Represents the result of processing the RedStone payload.
-///
-/// This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-/// particularly focusing on time-sensitive data and its associated values, according to the `Config`.
-#[derive(Debug, Eq, PartialEq)]
-pub struct ProcessorResult {
- /// The minimum timestamp encountered during processing.
- ///
- /// This field captures the earliest time point (in milliseconds since the Unix epoch)
- /// among the processed data packages, indicating the starting boundary of the dataset's time range.
- pub min_timestamp: u64,
-
- /// A collection of values processed during the operation.
- ///
- /// Each element in this vector represents a processed value corresponding
- /// to the passed data_feed item in the `Config`.
- pub values: Vec<U256>,
-}
-
-impl From<ProcessorResult> for (u64, Vec<U256>) {
- fn from(result: ProcessorResult) -> Self {
- (result.min_timestamp, result.values)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -
use crate::{
- core::config::Config,
- network::{
- assert::Assert,
- error::Error::{InsufficientSignerCount, TimestampTooFuture, TimestampTooOld},
- specific::U256,
- },
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- utils::filter::FilterSome,
-};
-
-/// A trait defining validation operations for data feeds and signers.
-///
-/// This trait specifies methods for validating aspects of data feeds and signers within a system that
-/// requires data integrity and authenticity checks. Implementations of this trait are responsible for
-/// defining the logic behind each validation step, ensuring that data conforms to expected rules and
-/// conditions.
-pub(crate) trait Validator {
- /// Retrieves the index of a given data feed.
- ///
- /// This method takes a `feed_id` representing the unique identifier of a data feed and
- /// returns an `Option<usize>` indicating the index of the feed within a collection of feeds.
- /// If the feed does not exist, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `feed_id`: `U256` - The unique identifier of the data feed.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the feed if it exists, or `None` if it does not.
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
-
- /// Retrieves the index of a given signer.
- ///
- /// This method accepts a signer identifier in the form of a byte slice and returns an
- /// `Option<usize>` indicating the signer's index within a collection of signers. If the signer
- /// is not found, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `signer`: `&[u8]` - A byte slice representing the signer's identifier.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the signer if found, or `None` if not found.
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
-
- /// Validates the signer count threshold for a given index within a set of values.
- ///
- /// This method is responsible for ensuring that the number of valid signers meets or exceeds
- /// a specified threshold necessary for a set of data values to be considered valid. It returns
- /// a vector of `U256` if the values pass the validation, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value being validated.
- /// * `values`: `&[Option<U256>]` - A slice of optional `U256` values associated with the data.
- ///
- /// # Returns
- ///
- /// * `Vec<U256>` - A vector of `U256` values that meet the validation criteria.
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256>;
-
- /// Validates the timestamp for a given index.
- ///
- /// This method checks whether a timestamp associated with a data value at a given index
- /// meets specific conditions (e.g., being within an acceptable time range). It returns
- /// the validated timestamp if it's valid, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value whose timestamp is being validated.
- /// * `timestamp`: `u64` - The timestamp to be validated.
- ///
- /// # Returns
- ///
- /// * `u64` - The validated timestamp.
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
-
-impl Validator for Config {
- #[inline]
- fn feed_index(&self, feed_id: U256) -> Option<usize> {
- self.feed_ids.iter().position(|&elt| elt == feed_id)
- }
-
- #[inline]
- fn signer_index(&self, signer: &[u8]) -> Option<usize> {
- self.signers
- .iter()
- .position(|elt| elt.to_ascii_lowercase() == signer.to_ascii_lowercase())
- }
-
- #[inline]
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256> {
- values.filter_some().assert_or_revert(
- |x| (*x).len() >= self.signer_count_threshold.into(),
- #[allow(clippy::useless_conversion)]
- |val| InsufficientSignerCount(index, val.len(), self.feed_ids[index]),
- )
- }
-
- #[inline]
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64 {
- timestamp.assert_or_revert(
- |&x| x + MAX_TIMESTAMP_DELAY_MS >= self.block_timestamp,
- |timestamp| TimestampTooOld(index, *timestamp),
- );
-
- timestamp.assert_or_revert(
- |&x| x <= self.block_timestamp + MAX_TIMESTAMP_AHEAD_MS,
- |timestamp| TimestampTooFuture(index, *timestamp),
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- test_helpers::{
- AVAX, BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- validator::Validator,
- },
- helpers::{
- hex::{hex_to_bytes, make_feed_id},
- iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- },
- network::specific::U256,
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- };
- use itertools::Itertools;
-
- #[test]
- fn test_feed_index() {
- let config = Config::test();
-
- let eth_index = config.feed_index(make_feed_id(ETH));
- assert_eq!(eth_index, 0.into());
-
- let eth_index = config.feed_index(make_feed_id("778680")); //eth
- assert_eq!(eth_index, None);
-
- let btc_index = config.feed_index(make_feed_id(BTC));
- assert_eq!(btc_index, 1.into());
-
- let avax_index = config.feed_index(make_feed_id(AVAX));
- assert_eq!(avax_index, None);
- }
-
- #[test]
- fn test_signer_index() {
- let config = Config::test();
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.into()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.to_uppercase()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.into()));
- assert_eq!(index, 1.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.replace('0', "1")));
- assert_eq!(index, None);
- }
-
- #[test]
- fn test_validate_timestamp() {
- let config = Config::test();
-
- config.validate_timestamp(0, TEST_BLOCK_TIMESTAMP);
- config.validate_timestamp(1, TEST_BLOCK_TIMESTAMP + 60000);
- config.validate_timestamp(2, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS);
- config.validate_timestamp(3, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS);
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP - 60000);
- }
-
- #[should_panic(expected = "Timestamp 2000000180001 is too future for #0")]
- #[test]
- fn test_validate_timestamp_too_future() {
- Config::test().validate_timestamp(0, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS + 1);
- }
-
- #[should_panic(expected = "Timestamp 1999999099999 is too old for #1")]
- #[test]
- fn test_validate_timestamp_too_old() {
- Config::test().validate_timestamp(1, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS - 1);
- }
-
- #[should_panic(expected = "Timestamp 0 is too old for #2")]
- #[test]
- fn test_validate_timestamp_zero() {
- Config::test().validate_timestamp(2, 0);
- }
-
- #[should_panic(expected = "Timestamp 4000000000000 is too future for #3")]
- #[test]
- fn test_validate_timestamp_big() {
- Config::test().validate_timestamp(3, TEST_BLOCK_TIMESTAMP + TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Timestamp 2000000000000 is too future for #4")]
- #[test]
- fn test_validate_timestamp_no_block_timestamp() {
- let mut config = Config::test();
-
- config.block_timestamp = 0;
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #0 (ETH)")]
- #[test]
- fn test_validate_signer_count_threshold_empty_list() {
- Config::test().validate_signer_count_threshold(0, vec![].as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_shorter_list() {
- Config::test().validate_signer_count_threshold(1, vec![1u8].iter_into_opt().as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_list_with_nones() {
- Config::test().validate_signer_count_threshold(
- 1,
- vec![None, 1u8.into(), None].opt_iter_into_opt().as_slice(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_size() {
- validate_with_all_permutations(vec![1u8, 2].iter_into_opt(), vec![1u8, 2].iter_into());
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_signer_count() {
- validate_with_all_permutations(
- vec![None, 1u8.into(), None, 2.into()].opt_iter_into_opt(),
- vec![1u8, 2].iter_into(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_larger_size() {
- validate_with_all_permutations(
- vec![
- 1u8.into(),
- None,
- None,
- 2.into(),
- 3.into(),
- None,
- 4.into(),
- None,
- ]
- .opt_iter_into_opt(),
- vec![1u8, 2, 3, 4].iter_into(),
- );
- }
-
- fn validate_with_all_permutations(numbers: Vec<Option<U256>>, expected_value: Vec<U256>) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
- let mut config = Config::test();
-
- let result = config.validate_signer_count_threshold(0, &numbers);
- assert_eq!(result, expected_value);
-
- for threshold in 0..expected_value.len() + 1 {
- config.signer_count_threshold = threshold as u8;
-
- for (index, perm) in perms.iter().enumerate() {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- let result =
- config.validate_signer_count_threshold(index % config.feed_ids.len(), &p);
- assert_eq!(result.len(), expected_value.len());
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -
use sha3::{Digest, Keccak256};
-
-pub fn keccak256(data: &[u8]) -> Box<[u8]> {
- Keccak256::new_with_prefix(data)
- .finalize()
- .as_slice()
- .into()
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{crypto::keccak256::keccak256, helpers::hex::hex_to_bytes};
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const EMPTY_MESSAGE_HASH: &str =
- "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
-
- #[test]
- fn test_keccak256() {
- let hash = keccak256(hex_to_bytes(MESSAGE.into()).as_slice());
-
- assert_eq!(hash.as_ref(), hex_to_bytes(MESSAGE_HASH.into()).as_slice());
- }
-
- #[test]
- fn test_keccak256_empty() {
- let hash = keccak256(vec![].as_slice());
-
- assert_eq!(
- hash.as_ref(),
- hex_to_bytes(EMPTY_MESSAGE_HASH.into()).as_slice()
- );
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -
use crate::crypto::{keccak256, recover::crypto256::recover_public_key};
-
-pub fn recover_address(message: Vec<u8>, signature: Vec<u8>) -> Vec<u8> {
- let recovery_byte = signature[64]; // 65-byte representation
- let msg_hash = keccak256::keccak256(message.as_slice());
- let key = recover_public_key(
- msg_hash,
- &signature[..64],
- recovery_byte - (if recovery_byte >= 27 { 27 } else { 0 }),
- );
- let key_hash = keccak256::keccak256(&key[1..]); // skip first uncompressed-key byte
-
- key_hash[12..].into() // last 20 bytes
-}
-
-#[cfg(feature = "crypto_secp256k1")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use secp256k1::{ecdsa::RecoverableSignature, Message, Secp256k1 as Secp256k1Curve};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let msg = Message::from_digest_slice(message_hash.as_ref())
- .unwrap_or_revert(|_| Error::CryptographicError(message_hash.len()));
-
- let recovery_id = secp256k1::ecdsa::RecoveryId::from_i32(recovery_byte.into())
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let sig: RecoverableSignature =
- RecoverableSignature::from_compact(signature_bytes, recovery_id)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let public_key = Secp256k1Curve::new().recover_ecdsa(&msg, &sig);
-
- public_key.unwrap().serialize_uncompressed().into()
- }
-}
-
-#[cfg(feature = "crypto_k256")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let recovery_id = RecoveryId::from_byte(recovery_byte)
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let signature = Signature::try_from(signature_bytes)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let recovered_key =
- VerifyingKey::recover_from_prehash(message_hash.as_ref(), &signature, recovery_id)
- .map(|key| key.to_encoded_point(false).to_bytes());
-
- recovered_key.unwrap()
- }
-}
-
-#[cfg(all(not(feature = "crypto_k256"), not(feature = "crypto_secp256k1")))]
-pub(crate) mod crypto256 {
- pub(crate) fn recover_public_key(
- _message_hash: Box<[u8]>,
- _signature_bytes: &[u8],
- _recovery_byte: u8,
- ) -> Box<[u8]> {
- panic!("Not implemented!")
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- crypto::recover::{crypto256::recover_public_key, recover_address},
- helpers::hex::hex_to_bytes,
- };
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const SIG_V27: &str = "475195641dae43318e194c3d9e5fc308773d6fdf5e197e02644dfd9ca3d19e3e2bd7d8656428f7f02e658a16b8f83722169c57126cc50bec8fad188b1bac6d19";
- const SIG_V28: &str = "c88242d22d88252c845b946c9957dbf3c7d59a3b69ecba2898198869f9f146ff268c3e47a11dbb05cc5198aadd659881817a59ee37e088d3253f4695927428c1";
- const PUBLIC_KEY_V27: &str =
- "04f5f035588502146774d0ccfd62ee5bf1d7f1dbb96aae33a79765c636b8ec75a36f5121931b5cc37215a7d4280c5700ca92daaaf93c32b06ca9f98b1f4ece624e";
- const PUBLIC_KEY_V28: &str =
- "04626f2ad2cfb0b41a24276d78de8959bcf45fc5e80804416e660aab2089d15e98206526e639ee19d17c8f9ae0ce3a6ff1a8ea4ab773d0fb4214e08aad7ba978c8";
- const ADDRESS_V27: &str = "2c59617248994D12816EE1Fa77CE0a64eEB456BF";
- const ADDRESS_V28: &str = "12470f7aBA85c8b81D63137DD5925D6EE114952b";
-
- #[test]
- fn test_recover_public_key_v27() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V27), 0);
-
- assert_eq!(u8_box(PUBLIC_KEY_V27), public_key);
- }
-
- #[test]
- fn test_recover_public_key_v28() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V28), 1);
-
- assert_eq!(u8_box(PUBLIC_KEY_V28), public_key);
- }
-
- #[test]
- fn test_recover_address_1b() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V27.to_owned() + "1b"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V27.into()), address);
- }
-
- #[test]
- fn test_recover_address_1c() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V28.to_owned() + "1c"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V28.into()), address);
- }
-
- fn u8_box(str: &str) -> Box<[u8]> {
- hex_to_bytes(str.into()).as_slice().into()
- }
-}
-
//! # RedStone
-//!
-//! `redstone` is a collection of utilities to make deserializing&decrypting RedStone payload.
-//! It contains a pure Rust implementation and also an extension for some networks.
-//!
-//! Different crypto-mechanisms are easily injectable.
-//! The current implementation contains `secp256k1`- and `k256`-based variants.
-
-pub mod core;
-mod crypto;
-pub mod network;
-mod protocol;
-mod utils;
-
-#[cfg(feature = "helpers")]
-pub mod helpers;
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -
extern crate alloc;
-
-use crate::network::specific::U256;
-use alloc::{format, string::String};
-
-pub trait AsHexStr {
- fn as_hex_str(&self) -> String;
-}
-
-impl AsHexStr for &[u8] {
- #[allow(clippy::format_collect)]
- fn as_hex_str(&self) -> String {
- self.iter().map(|byte| format!("{:02x}", byte)).collect()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsHexStr for casper_types::bytesrepr::Bytes {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- format!("{:X}", self)
- }
-}
-
-#[cfg(feature = "network_radix")]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- let digits = self.to_digits();
- let mut result = String::new();
- for &part in &digits {
- if result.is_empty() || part != 0u64 {
- result.push_str(&format!("{:02X}", part));
- }
- }
- result
- }
-}
-
-impl AsHexStr for Vec<u8> {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-impl AsHexStr for Box<[u8]> {
- fn as_hex_str(&self) -> String {
- self.as_ref().as_hex_str()
- }
-}
-
-pub trait AsAsciiStr {
- fn as_ascii_str(&self) -> String;
-}
-
-impl AsAsciiStr for &[u8] {
- fn as_ascii_str(&self) -> String {
- self.iter().map(|&code| code as char).collect()
- }
-}
-
-impl AsAsciiStr for Vec<u8> {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsAsciiStr for casper_types::bytesrepr::Bytes {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-impl AsAsciiStr for U256 {
- fn as_ascii_str(&self) -> String {
- let hex_string = self.as_hex_str();
- let bytes = (0..hex_string.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&hex_string[i..i + 2], 16))
- .collect::<Result<Vec<u8>, _>>()
- .unwrap();
-
- bytes.as_ascii_str()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
- };
-
- const ETH: u32 = 4543560u32;
-
- #[test]
- fn test_as_hex_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_hex_str();
-
- assert_eq!(result, "455448");
- }
-
- #[test]
- fn test_as_ascii_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_ascii_str();
-
- assert_eq!(result, "ETH");
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -
use crate::{
- network::{error::Error, specific::revert},
- print_debug,
-};
-use std::fmt::Debug;
-
-pub trait Assert<F> {
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
-
-impl<T, F> Assert<F> for T
-where
- T: Debug,
- F: Fn(&Self) -> bool,
-{
- fn assert_or_revert<E: FnOnce(&Self) -> Error>(self, check: F, error: E) -> Self {
- assert_or_revert(self, check, error)
- }
-}
-
-#[inline]
-fn assert_or_revert<F, T, E: FnOnce(&T) -> Error>(arg: T, check: F, error: E) -> T
-where
- F: Fn(&T) -> bool,
- T: Debug,
-{
- assert_or_revert_bool_with(check(&arg), || error(&arg));
-
- arg
-}
-
-#[inline]
-fn assert_or_revert_bool_with<E: FnOnce() -> Error>(check: bool, error: E) {
- if check {
- return;
- }
-
- let error = error();
- print_debug!("REVERT({}) - {}!", &error.code(), error);
- revert(error);
-}
-
-pub trait Unwrap<R> {
- type ErrorArg;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
-
-impl<T> Unwrap<T> for Option<T>
-where
- T: Debug,
-{
- type ErrorArg = ();
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(self, |arg| arg.is_some(), |_| error(&())).unwrap()
- }
-}
-
-impl<T, Err> Unwrap<T> for Result<T, Err>
-where
- T: Debug,
- Err: Debug,
-{
- type ErrorArg = Err;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(
- self,
- |arg| arg.is_ok(),
- |e| error(e.as_ref().err().unwrap()),
- )
- .unwrap()
- }
-}
-
-#[cfg(test)]
-mod assert_or_revert_tests {
- use crate::network::{
- assert::{assert_or_revert_bool_with, Assert},
- error::Error,
- };
-
- #[test]
- fn test_assert_or_revert_bool_with_true() {
- assert_or_revert_bool_with(true, || Error::ArrayIsEmpty);
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_assert_or_revert_bool_with_false() {
- assert_or_revert_bool_with(false, || Error::ArrayIsEmpty);
- }
-
- #[test]
- fn test_assert_or_revert_correct() {
- 5.assert_or_revert(|&x| x == 5, |&size| Error::SizeNotSupported(size));
- }
-
- #[should_panic(expected = "Size not supported: 5")]
- #[test]
- fn test_assert_or_revert_wrong() {
- 5.assert_or_revert(|&x| x < 5, |&size| Error::SizeNotSupported(size));
- }
-}
-
-#[cfg(test)]
-mod unwrap_or_revert_tests {
- use crate::network::{assert::Unwrap, error::Error};
-
- #[test]
- fn test_unwrap_or_revert_some() {
- let result = Some(543).unwrap_or_revert(|_| Error::CryptographicError(333));
-
- assert_eq!(result, 543);
- }
-
- #[should_panic(expected = "Cryptographic Error: 333")]
- #[test]
- fn test_unwrap_or_revert_none() {
- (Option::<u64>::None).unwrap_or_revert(|_| Error::CryptographicError(333));
- }
-
- #[test]
- fn test_unwrap_or_revert_ok() {
- let result = Ok(256).unwrap_or_revert(|_: &Error| Error::CryptographicError(333));
-
- assert_eq!(result, 256);
- }
-
- #[should_panic(expected = "Cryptographic Error: 567")]
- #[test]
- fn test_unwrap_or_revert_err() {
- Result::<&[u8], Error>::Err(Error::CryptographicError(567)).unwrap_or_revert(|e| e.clone());
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod error;
-mod from_bytes_repr;
-
-pub struct Casper;
-
-impl NetworkSpecific for Casper {
- type BytesRepr = casper_types::bytesrepr::Bytes;
- type ValueRepr = casper_types::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- casper_contract::contract_api::runtime::print(&_text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- casper_contract::contract_api::runtime::revert(error)
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -
use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
-};
-use std::fmt::{Debug, Display, Formatter};
-
-pub trait ContractErrorContent: Debug {
- fn code(&self) -> u8;
- fn message(&self) -> String;
-}
-
-/// Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-///
-/// These errors include issues with contract logic, data types,
-/// cryptographic operations, and conditions specific to the requirements.
-#[derive(Debug)]
-pub enum Error {
- /// Represents errors that arise from the contract itself.
- ///
- /// This variant is used for encapsulating errors that are specific to the contract's logic
- /// or execution conditions that aren't covered by more specific error types.
- ContractError(Box<dyn ContractErrorContent>),
-
- /// Indicates an overflow error with `U256` numbers.
- ///
- /// Used when operations on `U256` numbers exceed their maximum value, potentially leading
- /// to incorrect calculations or state.
- NumberOverflow(U256),
-
- /// Used when an expected non-empty array or vector is found to be empty.
- ///
- /// This could occur in scenarios where the contract logic requires a non-empty collection
- /// of items for the correct operation, for example, during aggregating the values.
- ArrayIsEmpty,
-
- /// Represents errors related to cryptographic operations.
- ///
- /// This includes failures in signature verification, hashing, or other cryptographic
- /// processes, with the usize indicating the position or identifier of the failed operation.
- CryptographicError(usize),
-
- /// Signifies that an unsupported size was encountered.
- ///
- /// This could be used when a data structure or input does not meet the expected size
- /// requirements for processing.
- SizeNotSupported(usize),
-
- /// Indicates that the marker bytes for RedStone are incorrect.
- ///
- /// This error is specific to scenarios where marker or identifier bytes do not match
- /// expected values, potentially indicating corrupted or tampered data.
- WrongRedStoneMarker(Vec<u8>),
-
- /// Used when there is leftover data in a payload that should have been empty.
- ///
- /// This could indicate an error in data parsing or that additional, unexpected data
- /// was included in a message or transaction.
- NonEmptyPayloadRemainder(Vec<u8>),
-
- /// Indicates that the number of signers does not meet the required threshold.
- ///
- /// This variant includes the current number of signers, the required threshold, and
- /// potentially a feed_id related to the operation that failed due to insufficient signers.
- InsufficientSignerCount(usize, usize, U256),
-
- /// Used when a timestamp is older than allowed by the processor logic.
- ///
- /// Includes the position or identifier of the timestamp and the threshold value,
- /// indicating that the provided timestamp is too far in the past.
- TimestampTooOld(usize, u64),
-
- /// Indicates that a timestamp is further in the future than allowed.
- ///
- /// Similar to `TimestampTooOld`, but for future timestamps exceeding the contract's
- /// acceptance window.
- TimestampTooFuture(usize, u64),
-
- /// Represents errors that need to clone `ContractErrorContent`, which is not supported by default.
- ///
- /// This variant allows for the manual duplication of contract error information, including
- /// an error code and a descriptive message.
- ClonedContractError(u8, String),
-}
-
-impl Error {
- pub fn contract_error<T: ContractErrorContent + 'static>(value: T) -> Error {
- Error::ContractError(Box::new(value))
- }
-
- pub(crate) fn code(&self) -> u16 {
- match self {
- Error::ContractError(boxed) => boxed.code() as u16,
- Error::NumberOverflow(_) => 509,
- Error::ArrayIsEmpty => 510,
- Error::WrongRedStoneMarker(_) => 511,
- Error::NonEmptyPayloadRemainder(_) => 512,
- Error::InsufficientSignerCount(data_package_index, value, _) => {
- (2000 + data_package_index * 10 + value) as u16
- }
- Error::SizeNotSupported(size) => 600 + *size as u16,
- Error::CryptographicError(size) => 700 + *size as u16,
- Error::TimestampTooOld(data_package_index, _) => 1000 + *data_package_index as u16,
- Error::TimestampTooFuture(data_package_index, _) => 1050 + *data_package_index as u16,
- Error::ClonedContractError(code, _) => *code as u16,
- }
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- Error::ContractError(boxed) => write!(f, "Contract error: {}", boxed.message()),
- Error::NumberOverflow(number) => write!(f, "Number overflow: {}", number),
- Error::ArrayIsEmpty => write!(f, "Array is empty"),
- Error::CryptographicError(size) => write!(f, "Cryptographic Error: {}", size),
- Error::SizeNotSupported(size) => write!(f, "Size not supported: {}", size),
- Error::WrongRedStoneMarker(bytes) => {
- write!(f, "Wrong RedStone marker: {}", bytes.as_hex_str())
- }
- Error::NonEmptyPayloadRemainder(bytes) => {
- write!(f, "Non empty payload remainder: {}", bytes.as_hex_str())
- }
- Error::InsufficientSignerCount(data_package_index, value, feed_id) => write!(
- f,
- "Insufficient signer count {} for #{} ({})",
- value,
- data_package_index,
- feed_id.as_ascii_str()
- ),
- Error::TimestampTooOld(data_package_index, value) => {
- write!(
- f,
- "Timestamp {} is too old for #{}",
- value, data_package_index
- )
- }
- Error::TimestampTooFuture(data_package_index, value) => write!(
- f,
- "Timestamp {} is too future for #{}",
- value, data_package_index
- ),
- Error::ClonedContractError(_, message) => {
- write!(f, "(Cloned) Contract error: {}", message)
- }
- }
- }
-}
-
-impl Clone for Error {
- fn clone(&self) -> Self {
- match self {
- Error::ContractError(content) => {
- Error::ClonedContractError(content.code(), content.message())
- }
- Error::NumberOverflow(value) => Error::NumberOverflow(*value),
- Error::ArrayIsEmpty => Error::ArrayIsEmpty,
- Error::CryptographicError(size) => Error::CryptographicError(*size),
- Error::SizeNotSupported(size) => Error::SizeNotSupported(*size),
- Error::WrongRedStoneMarker(bytes) => Error::WrongRedStoneMarker(bytes.clone()),
- Error::NonEmptyPayloadRemainder(bytes) => {
- Error::NonEmptyPayloadRemainder(bytes.clone())
- }
- Error::InsufficientSignerCount(count, needed, bytes) => {
- Error::InsufficientSignerCount(*count, *needed, *bytes)
- }
- Error::TimestampTooOld(index, timestamp) => Error::TimestampTooOld(*index, *timestamp),
- Error::TimestampTooFuture(index, timestamp) => {
- Error::TimestampTooFuture(*index, *timestamp)
- }
- Error::ClonedContractError(code, message) => {
- Error::ClonedContractError(*code, message.as_str().into())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -
use crate::network::specific::Bytes;
-
-pub trait Flattened<T> {
- fn flattened(&self) -> T;
-}
-
-impl Flattened<Bytes> for Vec<Bytes> {
- fn flattened(&self) -> Bytes {
- #[allow(clippy::useless_conversion)]
- self.iter().flatten().copied().collect::<Vec<_>>().into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{flattened::Flattened, specific::Bytes};
-
- #[test]
- fn test_bytes_flattened() {
- #[allow(clippy::useless_conversion)]
- let bytes: Vec<Bytes> = vec![
- vec![1u8, 2, 3].into(),
- vec![4u8].into(),
- vec![].into(),
- vec![5, 6, 7].into(),
- ];
-
- let result: Bytes = bytes.flattened();
-
- #[allow(clippy::useless_conversion)]
- let expected_result: Bytes = vec![1u8, 2, 3, 4, 5, 6, 7].into();
-
- assert_eq!(result, expected_result);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -
use crate::network::specific::VALUE_SIZE;
-
-pub trait FromBytesRepr<T> {
- fn from_bytes_repr(bytes: T) -> Self;
-}
-
-pub trait Sanitized {
- fn sanitized(self) -> Self;
-}
-
-impl Sanitized for Vec<u8> {
- fn sanitized(self) -> Self {
- if self.len() <= VALUE_SIZE {
- return self;
- }
-
- let index = self.len().max(VALUE_SIZE) - VALUE_SIZE;
- let remainder = &self[0..index];
-
- if remainder != vec![0; index] {
- panic!("Number to big: {:?} digits", self.len())
- }
-
- self[index..].into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- };
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[test]
- fn test_from_bytes_repr_single() {
- let vec = vec![1];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(1u32));
- }
-
- #[test]
- fn test_from_bytes_repr_double() {
- let vec = vec![1, 2];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(258u32));
- }
-
- #[test]
- fn test_from_bytes_repr_simple() {
- let vec = vec![1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[test]
- fn test_from_bytes_repr_bigger() {
- let vec = vec![101, 202, 255];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(6671103u32));
- }
-
- #[test]
- fn test_from_bytes_repr_empty() {
- let result = U256::from_bytes_repr(Vec::new());
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[test]
- fn test_from_bytes_repr_trailing_zeroes() {
- let vec = vec![1, 2, 3, 0];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(16909056u32));
- }
-
- #[test]
- fn test_from_bytes_repr_leading_zeroes() {
- let vec = vec![0, 1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_max() {
- let vec = vec![255; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-
- #[test]
- fn test_from_bytes_repr_min() {
- let vec = vec![0; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[should_panic(expected = "Number to big")]
- #[test]
- fn test_from_bytes_repr_too_long() {
- let x = VALUE_SIZE as u8 + 1;
- let vec = (1..=x).collect();
-
- U256::from_bytes_repr(vec);
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_too_long_but_zeroes() {
- let mut vec = vec![255; VALUE_SIZE + 1];
- vec[0] = 0;
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-}
-
pub mod as_str;
-pub mod assert;
-pub mod error;
-pub mod from_bytes_repr;
-pub mod print_debug;
-pub mod specific;
-
-#[cfg(feature = "network_casper")]
-pub mod casper;
-
-#[cfg(feature = "network_casper")]
-pub type _Network = casper::Casper;
-
-#[cfg(feature = "network_radix")]
-pub mod radix;
-
-#[cfg(feature = "network_radix")]
-pub type _Network = radix::Radix;
-
-pub mod flattened;
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-mod pure;
-
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-pub type _Network = pure::Std;
-
extern crate alloc;
-
-#[macro_export]
-macro_rules! print_debug {
- ($fmt:expr) => {
- $crate::network::specific::print(format!($fmt))
- };
- ($fmt:expr, $($args:tt)*) => {
- $crate::network::specific::print(format!($fmt, $($args)*))
- };
-}
-
-#[macro_export]
-macro_rules! print_and_panic {
- ($fmt:expr) => {{
- $crate::print_debug!($fmt);
- panic!($fmt)
- }};
- ($fmt:expr, $($args:tt)*) => {{
- $crate::print_debug!($fmt, $($args)*);
- panic!($fmt, $($args)*)
- }};
-}
-
use crate::network::{error::Error, specific::NetworkSpecific};
-use primitive_types::U256;
-use std::eprintln;
-
-mod from_bytes_repr;
-
-pub struct Std;
-
-impl NetworkSpecific for Std {
- type BytesRepr = Vec<u8>;
- type ValueRepr = U256;
- type _Self = Std;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(text: String) {
- eprintln!("{}", text)
- }
-
- fn revert(error: Error) -> ! {
- panic!("{}", error)
- }
-}
-
use crate::network::{
- from_bytes_repr::{FromBytesRepr, Sanitized},
- specific::U256,
-};
-
-impl FromBytesRepr<Vec<u8>> for U256 {
- fn from_bytes_repr(bytes: Vec<u8>) -> Self {
- match bytes.len() {
- 0 => U256::ZERO,
- 1 => U256::from(bytes[0]),
- _ => {
- // TODO: make it cheaper
- let mut bytes_le = bytes.sanitized();
- bytes_le.reverse();
-
- U256::from_le_bytes(bytes_le.as_slice())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod from_bytes_repr;
-pub mod u256_ext;
-
-pub struct Radix;
-
-impl NetworkSpecific for Radix {
- type BytesRepr = Vec<u8>;
- type ValueRepr = radix_common::math::bnum_integer::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- scrypto::prelude::info!("{}", _text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- scrypto::prelude::Runtime::panic(error.to_string())
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
use crate::network::{_Network, error::Error, from_bytes_repr::FromBytesRepr};
-
-pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
-
-pub(crate) type Network = <_Network as NetworkSpecific>::_Self;
-pub type Bytes = <_Network as NetworkSpecific>::BytesRepr;
-pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
-pub const VALUE_SIZE: usize = <_Network as NetworkSpecific>::VALUE_SIZE;
-
-pub fn print(_text: String) {
- Network::print(_text)
-}
-
-pub fn revert(error: Error) -> ! {
- Network::revert(error)
-}
-
pub(crate) const UNSIGNED_METADATA_BYTE_SIZE_BS: usize = 3;
-pub(crate) const DATA_PACKAGES_COUNT_BS: usize = 2;
-pub(crate) const DATA_POINTS_COUNT_BS: usize = 3;
-pub(crate) const SIGNATURE_BS: usize = 65;
-pub(crate) const DATA_POINT_VALUE_BYTE_SIZE_BS: usize = 4;
-pub(crate) const DATA_FEED_ID_BS: usize = 32;
-pub(crate) const TIMESTAMP_BS: usize = 6;
-pub(crate) const MAX_TIMESTAMP_DELAY_MS: u64 = 15 * 60 * 1000; // 15 minutes in milliseconds
-pub(crate) const MAX_TIMESTAMP_AHEAD_MS: u64 = 3 * 60 * 1000; // 3 minutes in milliseconds
-pub(crate) const REDSTONE_MARKER_BS: usize = 9;
-pub(crate) const REDSTONE_MARKER: [u8; 9] = [0, 0, 2, 237, 87, 1, 30, 0, 0]; // 0x000002ed57011e0000
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -
use crate::{
- crypto::recover::recover_address,
- network::as_str::AsHexStr,
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_point::{trim_data_points, DataPoint},
- },
- utils::trim::Trim,
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
-
-pub(crate) fn trim_data_packages(payload: &mut Vec<u8>, count: usize) -> Vec<DataPackage> {
- let mut data_packages = Vec::new();
-
- for _ in 0..count {
- let data_package = trim_data_package(payload);
- data_packages.push(data_package);
- }
-
- data_packages
-}
-
-fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage {
- let signature = payload.trim_end(SIGNATURE_BS);
- let mut tmp = payload.clone();
-
- let data_point_count = payload.trim_end(DATA_POINTS_COUNT_BS);
- let value_size = payload.trim_end(DATA_POINT_VALUE_BYTE_SIZE_BS);
- let timestamp = payload.trim_end(TIMESTAMP_BS);
- let size = data_point_count * (value_size + DATA_FEED_ID_BS)
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + DATA_POINTS_COUNT_BS;
-
- let signable_bytes = tmp.trim_end(size);
- let signer_address = recover_address(signable_bytes, signature);
-
- let data_points = trim_data_points(payload, data_point_count, value_size);
-
- DataPackage {
- data_points,
- timestamp,
- signer_address,
- }
-}
-
-impl Debug for DataPackage {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPackage {{\n signer_address: 0x{}, timestamp: {},\n data_points: {:?}\n}}",
- self.signer_address.as_hex_str(),
- self.timestamp,
- self.data_points
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{from_bytes_repr::FromBytesRepr, specific::U256},
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_package::{trim_data_package, trim_data_packages, DataPackage},
- data_point::DataPoint,
- },
- };
-
- const DATA_PACKAGE_BYTES_1: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e018d79bf0ba00000002000000151afa8c5c3caf6004b42c0fb17723e524f993b9ecbad3b9bce5ec74930fa436a3660e8edef10e96ee5f222de7ef5787c02ca467c0ec18daa2907b43ac20c63c11c";
- const DATA_PACKAGE_BYTES_2: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cdd851e018d79bf0ba000000020000001473fd9dc72e6814a7de719b403cf4c9eba08934a643fd0666c433b806b31e69904f2226ffd3c8ef75861b11b5e32a1fda4b1458e0da4605a772dfba2a812f3ee1b";
-
- const SIGNER_ADDRESS_1: &str = "1ea62d73edf8ac05dfcea1a34b9796e937a29eff";
- const SIGNER_ADDRESS_2: &str = "109b4a318a4f5ddcbca6349b45f881b4137deafb";
-
- const VALUE_1: u128 = 232141080910;
- const VALUE_2: u128 = 232144078110;
-
- const DATA_PACKAGE_SIZE: usize = 32
- + DATA_FEED_ID_BS
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + SIGNATURE_BS
- + DATA_POINTS_COUNT_BS;
-
- #[test]
- fn test_trim_data_packages() {
- test_trim_data_packages_of(2, "");
- test_trim_data_packages_of(0, "");
- test_trim_data_packages_of(1, "");
- }
-
- #[test]
- fn test_trim_data_packages_with_prefix() {
- let prefix = "da4687f1914a1c";
-
- test_trim_data_packages_of(2, prefix);
- }
-
- #[test]
- fn test_trim_data_packages_single() {
- let mut bytes = hex_to_bytes(DATA_PACKAGE_BYTES_1.into());
- let data_packages = trim_data_packages(&mut bytes, 1);
- assert_eq!(data_packages.len(), 1);
- assert_eq!(bytes, Vec::<u8>::new());
-
- verify_data_package(data_packages[0].clone(), VALUE_1, SIGNER_ADDRESS_1);
- }
-
- fn test_trim_data_packages_of(count: usize, prefix: &str) {
- let input: Vec<u8> =
- hex_to_bytes((prefix.to_owned() + DATA_PACKAGE_BYTES_1) + DATA_PACKAGE_BYTES_2);
- let mut bytes = input.clone();
- let data_packages = trim_data_packages(&mut bytes, count);
-
- assert_eq!(data_packages.len(), count);
- assert_eq!(
- bytes.as_slice(),
- &input[..input.len() - count * DATA_PACKAGE_SIZE]
- );
-
- let values = &[VALUE_2, VALUE_1];
- let signers = &[SIGNER_ADDRESS_2, SIGNER_ADDRESS_1];
-
- for i in 0..count {
- verify_data_package(data_packages[i].clone(), values[i], signers[i]);
- }
- }
-
- #[should_panic(expected = "index out of bounds")]
- #[test]
- fn test_trim_data_packages_bigger_number() {
- test_trim_data_packages_of(3, "");
- }
-
- #[test]
- fn test_trim_data_package() {
- test_trim_data_package_of(DATA_PACKAGE_BYTES_1, VALUE_1, SIGNER_ADDRESS_1);
- test_trim_data_package_of(DATA_PACKAGE_BYTES_2, VALUE_2, SIGNER_ADDRESS_2);
- }
-
- #[test]
- fn test_trim_data_package_with_prefix() {
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_1),
- VALUE_1,
- SIGNER_ADDRESS_1,
- );
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_2),
- VALUE_2,
- SIGNER_ADDRESS_2,
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_signature_only() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1[(DATA_PACKAGE_BYTES_1.len() - 2 * SIGNATURE_BS)..],
- 0,
- "",
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_shorter() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1
- [(DATA_PACKAGE_BYTES_1.len() - 2 * (SIGNATURE_BS + DATA_POINTS_COUNT_BS))..],
- 0,
- "",
- );
- }
-
- fn test_trim_data_package_of(bytes_str: &str, expected_value: u128, signer_address: &str) {
- let mut bytes: Vec<u8> = hex_to_bytes(bytes_str.into());
- let result = trim_data_package(&mut bytes);
- assert_eq!(
- bytes,
- hex_to_bytes(bytes_str[..bytes_str.len() - 2 * (DATA_PACKAGE_SIZE)].into())
- );
-
- verify_data_package(result, expected_value, signer_address);
- }
-
- fn verify_data_package(result: DataPackage, expected_value: u128, signer_address: &str) {
- let data_package = DataPackage {
- data_points: vec![DataPoint {
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_PACKAGE_BYTES_1[..6].into())),
- value: U256::from(expected_value),
- }],
- timestamp: 1707144580000,
- signer_address: hex_to_bytes(signer_address.into()),
- };
-
- assert_eq!(result, data_package);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -
use crate::{
- network::{
- as_str::{AsAsciiStr, AsHexStr},
- assert::Assert,
- error::Error,
- from_bytes_repr::FromBytesRepr,
- specific::U256,
- },
- protocol::constants::DATA_FEED_ID_BS,
- utils::{trim::Trim, trim_zeros::TrimZeros},
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
-
-pub(crate) fn trim_data_points(
- payload: &mut Vec<u8>,
- count: usize,
- value_size: usize,
-) -> Vec<DataPoint> {
- count.assert_or_revert(|&count| count == 1, |&count| Error::SizeNotSupported(count));
-
- let mut data_points = Vec::new();
-
- for _ in 0..count {
- let data_point = trim_data_point(payload, value_size);
- data_points.push(data_point);
- }
-
- data_points
-}
-
-fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint {
- let value = payload.trim_end(value_size);
- let feed_id: Vec<u8> = payload.trim_end(DATA_FEED_ID_BS);
-
- DataPoint {
- value,
- feed_id: U256::from_bytes_repr(feed_id.trim_zeros()),
- }
-}
-
-impl Debug for DataPoint {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPoint {{\n feed_id: {:?} (0x{}), value: {}\n }}",
- self.feed_id.as_ascii_str(),
- self.feed_id.as_hex_str(),
- self.value,
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- },
- protocol::{
- constants::DATA_FEED_ID_BS,
- data_point::{trim_data_point, trim_data_points, DataPoint},
- },
- };
- use std::ops::Shr;
-
- const DATA_POINT_BYTES_TAIL: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e";
- const VALUE: u128 = 232141080910;
-
- #[test]
- fn test_trim_data_points() {
- let mut bytes = hex_to_bytes(DATA_POINT_BYTES_TAIL.into());
- let result = trim_data_points(&mut bytes, 1, 32);
-
- assert_eq!(result.len(), 1);
-
- verify_rest_and_result(
- DATA_POINT_BYTES_TAIL,
- 32,
- VALUE.into(),
- bytes,
- result[0].clone(),
- )
- }
-
- #[should_panic(expected = "Size not supported: 0")]
- #[test]
- fn test_trim_zero_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 0, 32);
- }
-
- #[should_panic(expected = "Size not supported: 2")]
- #[test]
- fn test_trim_two_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 2, 32);
- }
-
- #[test]
- fn test_trim_data_point() {
- test_trim_data_point_of(DATA_POINT_BYTES_TAIL, 32, VALUE.into());
- }
-
- #[test]
- fn test_trim_data_point_with_prefix() {
- test_trim_data_point_of(
- &("a2a812f3ee1b".to_owned() + DATA_POINT_BYTES_TAIL),
- 32,
- VALUE.into(),
- );
- }
-
- #[test]
- fn test_trim_data_point_other_lengths() {
- for i in 1..VALUE_SIZE {
- test_trim_data_point_of(
- &DATA_POINT_BYTES_TAIL[..DATA_POINT_BYTES_TAIL.len() - 2 * i],
- 32 - i,
- U256::from(VALUE).shr(8 * i as u32),
- );
- }
- }
-
- fn test_trim_data_point_of(value: &str, size: usize, expected_value: U256) {
- let mut bytes = hex_to_bytes(value.into());
- let result = trim_data_point(&mut bytes, size);
-
- verify_rest_and_result(value, size, expected_value, bytes, result);
- }
-
- fn verify_rest_and_result(
- value: &str,
- size: usize,
- expected_value: U256,
- rest: Vec<u8>,
- result: DataPoint,
- ) {
- assert_eq!(
- rest,
- hex_to_bytes(value[..value.len() - 2 * (size + DATA_FEED_ID_BS)].into())
- );
-
- let data_point = DataPoint {
- value: expected_value,
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_POINT_BYTES_TAIL[..6].to_string())),
- };
-
- assert_eq!(result, data_point);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
-};
-
-pub fn trim_redstone_marker(payload: &mut Vec<u8>) {
- let marker: Vec<u8> = payload.trim_end(REDSTONE_MARKER_BS);
-
- marker.as_slice().assert_or_revert(
- |&marker| marker == REDSTONE_MARKER,
- |&val| Error::WrongRedStoneMarker(val.into()),
- );
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- protocol::{constants::REDSTONE_MARKER_BS, marker::trim_redstone_marker},
- };
-
- const PAYLOAD_TAIL: &str = "1c000f000000000002ed57011e0000";
-
- #[test]
- fn test_trim_redstone_marker() {
- let mut bytes = hex_to_bytes(PAYLOAD_TAIL.into());
- trim_redstone_marker(&mut bytes);
-
- assert_eq!(
- bytes,
- hex_to_bytes(PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2 * REDSTONE_MARKER_BS].into())
- );
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 000002ed57022e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong() {
- trim_redstone_marker(&mut hex_to_bytes(PAYLOAD_TAIL.replace('1', "2")));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 00000002ed57011e00")]
- #[test]
- fn test_trim_redstone_marker_wrong_ending() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2].into(),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 100002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong_beginning() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL.replace("0000000", "1111111"),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 0002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_too_short() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[PAYLOAD_TAIL.len() - 2 * (REDSTONE_MARKER_BS - 1)..].into(),
- ));
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::{
- constants::{DATA_PACKAGES_COUNT_BS, UNSIGNED_METADATA_BYTE_SIZE_BS},
- data_package::{trim_data_packages, DataPackage},
- marker,
- },
- utils::trim::Trim,
-};
-
-#[derive(Clone, Debug)]
-pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
-
-impl Payload {
- pub(crate) fn make(payload_bytes: &mut Vec<u8>) -> Payload {
- marker::trim_redstone_marker(payload_bytes);
- let payload = trim_payload(payload_bytes);
-
- payload_bytes.assert_or_revert(
- |bytes| bytes.is_empty(),
- |bytes| Error::NonEmptyPayloadRemainder(bytes.as_slice().into()),
- );
-
- payload
- }
-}
-
-fn trim_payload(payload: &mut Vec<u8>) -> Payload {
- let data_package_count = trim_metadata(payload);
- let data_packages = trim_data_packages(payload, data_package_count);
-
- Payload { data_packages }
-}
-
-fn trim_metadata(payload: &mut Vec<u8>) -> usize {
- let unsigned_metadata_size = payload.trim_end(UNSIGNED_METADATA_BYTE_SIZE_BS);
- let _: Vec<u8> = payload.trim_end(unsigned_metadata_size);
-
- payload.trim_end(DATA_PACKAGES_COUNT_BS)
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::{hex_to_bytes, read_payload_bytes, read_payload_hex},
- protocol::{
- constants::REDSTONE_MARKER_BS,
- payload::{trim_metadata, trim_payload, Payload},
- },
- };
-
- const PAYLOAD_METADATA_BYTES: &str = "000f000000";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTE: &str = "000f55000001";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTES: &str = "000f11223344556677889900aabbccddeeff000010";
-
- #[test]
- fn test_trim_metadata() {
- let prefix = "9e0294371c";
-
- for &bytes_str in &[
- PAYLOAD_METADATA_BYTES,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTE,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTES,
- ] {
- let mut bytes = hex_to_bytes(prefix.to_owned() + bytes_str);
- let result = trim_metadata(&mut bytes);
-
- assert_eq!(bytes, hex_to_bytes(prefix.into()));
- assert_eq!(result, 15);
- }
- }
-
- #[test]
- fn test_trim_payload() {
- let payload_hex = read_payload_bytes("./sample-data/payload.hex");
-
- let mut bytes = payload_hex[..payload_hex.len() - REDSTONE_MARKER_BS].into();
- let payload = trim_payload(&mut bytes);
-
- assert_eq!(bytes, Vec::<u8>::new());
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[test]
- fn test_make_payload() {
- let mut payload_hex = read_payload_bytes("./sample-data/payload.hex");
- let payload = Payload::make(&mut payload_hex);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[should_panic(expected = "Non empty payload remainder: 12")]
- #[test]
- fn test_make_payload_with_prefix() {
- let payload_hex = read_payload_hex("./sample-data/payload.hex");
- let mut bytes = hex_to_bytes("12".to_owned() + &payload_hex);
- let payload = Payload::make(&mut bytes);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-}
-
pub(crate) trait FilterSome<Output> {
- fn filter_some(&self) -> Output;
-}
-
-impl<T: Copy> FilterSome<Vec<T>> for [Option<T>] {
- fn filter_some(&self) -> Vec<T> {
- self.iter().filter_map(|&opt| opt).collect()
- }
-}
-
-#[cfg(test)]
-mod filter_some_tests {
- use crate::utils::filter::FilterSome;
-
- #[test]
- fn test_filter_some() {
- let values = [None, Some(23u64), None, Some(12), Some(12), None, Some(23)];
-
- assert_eq!(values.filter_some(), vec![23, 12, 12, 23])
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -
use crate::network::{assert::Assert, error::Error::ArrayIsEmpty, specific::U256};
-use std::ops::{Add, Rem, Shr};
-
-pub(crate) trait Median {
- type Item;
-
- fn median(self) -> Self::Item;
-}
-
-trait Avg {
- fn avg(self, other: Self) -> Self;
-}
-
-trait Averageable:
- Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy
-{
-}
-
-impl Averageable for i32 {}
-
-#[cfg(feature = "network_radix")]
-impl Avg for U256 {
- fn avg(self, other: Self) -> Self {
- let one = 1u32;
- let two = U256::from(2u8);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl Averageable for U256 {}
-
-impl<T> Avg for T
-where
- T: Averageable,
-{
- fn avg(self, other: Self) -> Self {
- let one = T::from(1);
- let two = T::from(2);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-impl<T> Median for Vec<T>
-where
- T: Copy + Ord + Avg,
-{
- type Item = T;
-
- fn median(self) -> Self::Item {
- let len = self.len();
-
- match len.assert_or_revert(|x| *x > 0, |_| ArrayIsEmpty) {
- 1 => self[0],
- 2 => self[0].avg(self[1]),
- 3 => maybe_pick_median(self[0], self[1], self[2]).unwrap_or_else(|| {
- maybe_pick_median(self[1], self[0], self[2])
- .unwrap_or_else(|| maybe_pick_median(self[1], self[2], self[0]).unwrap())
- }),
- _ => {
- let mut values = self;
- values.sort();
-
- let mid = len / 2;
-
- if len % 2 == 0 {
- values[mid - 1].avg(values[mid])
- } else {
- values[mid]
- }
- }
- }
- }
-}
-
-#[inline]
-fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>
-where
- T: PartialOrd,
-{
- if (b >= a && b <= c) || (b >= c && b <= a) {
- Some(b)
- } else {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{Avg, Median};
- use crate::network::specific::U256;
- use itertools::Itertools;
- use std::fmt::Debug;
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_avg() {
- let u256 = U256::max_value(); // 115792089237316195423570985008687907853269984665640564039457584007913129639935
- let u256_max_sub_1 = u256 - U256::from(1u32);
- let u256max_div_2 = u256 / U256::from(2u32);
-
- assert_eq!(u256.avg(U256::from(0u8)), u256max_div_2);
- assert_eq!(u256.avg(U256::from(1u8)), u256max_div_2 + U256::from(1u8));
- assert_eq!(u256.avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!(u256.avg(u256), u256);
-
- assert_eq!((u256_max_sub_1).avg(U256::from(0u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(U256::from(1u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!((u256_max_sub_1).avg(u256), u256_max_sub_1);
- }
-
- #[test]
- #[should_panic(expected = "Array is empty")]
- fn test_median_empty_vector() {
- let vec: Vec<i32> = vec![];
-
- vec.median();
- }
-
- #[test]
- fn test_median_single_element() {
- assert_eq!(vec![1].median(), 1);
- }
-
- #[test]
- fn test_median_two_elements() {
- test_all_permutations(vec![1, 3], 2);
- test_all_permutations(vec![1, 2], 1);
- test_all_permutations(vec![1, 1], 1);
- }
-
- #[test]
- fn test_median_three_elements() {
- test_all_permutations(vec![1, 2, 3], 2);
- test_all_permutations(vec![1, 1, 2], 1);
- test_all_permutations(vec![1, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1], 1);
- }
-
- #[test]
- fn test_median_even_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4], 2);
- test_all_permutations(vec![1, 2, 4, 4], 3);
- test_all_permutations(vec![1, 1, 3, 3], 2);
- test_all_permutations(vec![1, 1, 3, 4], 2);
- test_all_permutations(vec![1, 1, 1, 3], 1);
- test_all_permutations(vec![1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 1, 1, 1], 1);
- test_all_permutations(vec![1, 2, 3, 4, 5, 6], 3);
- }
-
- #[test]
- fn test_median_odd_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 1, 4, 5], 1);
- test_all_permutations(vec![1, 1, 1, 3, 3], 1);
- test_all_permutations(vec![1, 1, 3, 3, 5], 3);
-
- test_all_permutations(vec![1, 2, 3, 5, 5], 3);
- test_all_permutations(vec![1, 2, 5, 5, 5], 5);
- test_all_permutations(vec![1, 1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 3, 3, 5, 5], 3);
-
- test_all_permutations(vec![1, 2, 2, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1, 1, 2], 1);
- test_all_permutations(vec![1, 1, 1, 1, 1], 1);
-
- test_all_permutations(vec![1, 2, 3, 4, 5, 6, 7], 4);
- }
-
- fn test_all_permutations<T: Copy + Ord + Avg + Debug>(numbers: Vec<T>, expected_value: T) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
-
- for perm in perms {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- assert_eq!(p.median(), expected_value);
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -
use crate::network::{
- assert::Unwrap, error::Error, from_bytes_repr::FromBytesRepr, specific::U256,
-};
-
-pub trait Trim<T>
-where
- Self: Sized,
-{
- fn trim_end(&mut self, len: usize) -> T;
-}
-
-impl Trim<Vec<u8>> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> Self {
- if len >= self.len() {
- std::mem::take(self)
- } else {
- self.split_off(self.len() - len)
- }
- }
-}
-
-impl Trim<U256> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> U256 {
- U256::from_bytes_repr(self.trim_end(len))
- }
-}
-
-impl Trim<usize> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> usize {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-impl Trim<u64> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> u64 {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{
- network::specific::U256,
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
- };
-
- const MARKER_DECIMAL: u64 = 823907890102272;
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.into()
- }
-
- #[test]
- fn test_trim_end_number() {
- let (rest, result): (_, U256) = test_trim_end(3);
- assert_eq!(result, (256u32.pow(2) * 30).into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER[..6]);
-
- let (_, result): (_, u64) = test_trim_end(3);
- assert_eq!(result, 256u64.pow(2) * 30);
-
- let (_, result): (_, usize) = test_trim_end(3);
- assert_eq!(result, 256usize.pow(2) * 30);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(3);
- assert_eq!(result.as_slice(), &REDSTONE_MARKER[6..]);
- }
-
- #[test]
- fn test_trim_end_number_null() {
- let (rest, result): (_, U256) = test_trim_end(0);
- assert_eq!(result, 0u32.into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER);
-
- let (_, result): (_, u64) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, usize) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(0);
- assert_eq!(result, Vec::<u8>::new());
- }
-
- #[test]
- fn test_trim_end_whole() {
- test_trim_end_whole_size(REDSTONE_MARKER_BS);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 1);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 2);
- test_trim_end_whole_size(REDSTONE_MARKER_BS + 1);
- }
-
- fn test_trim_end_whole_size(size: usize) {
- let (rest, result): (_, U256) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL.into());
- assert_eq!(
- rest.as_slice().len(),
- REDSTONE_MARKER_BS - size.min(REDSTONE_MARKER_BS)
- );
-
- let (_, result): (_, u64) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL);
-
- let (_, result): (_, usize) = test_trim_end(size);
- assert_eq!(result, 823907890102272usize);
-
- let (_rest, result): (_, Vec<u8>) = test_trim_end(size);
- assert_eq!(result.as_slice().len(), size.min(REDSTONE_MARKER_BS));
- }
-
- #[test]
- fn test_trim_end_u64() {
- let mut bytes = vec![255, 255, 255, 255, 255, 255, 255, 255, 255];
- let x: u64 = bytes.trim_end(8);
-
- let expected_bytes = vec![255];
-
- assert_eq!(bytes, expected_bytes);
- assert_eq!(x, 18446744073709551615);
- }
-
- #[should_panic(expected = "Number overflow: 18591708106338011145")]
- #[test]
- fn test_trim_end_u64_overflow() {
- let mut bytes = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9];
-
- let _: u64 = bytes.trim_end(9);
- }
-
- #[allow(dead_code)]
- trait TestTrimEnd<T>
- where
- Self: Sized,
- {
- fn test_trim_end(size: usize) -> (Self, T);
- }
-
- fn test_trim_end<T>(size: usize) -> (Vec<u8>, T)
- where
- Vec<u8>: Trim<T>,
- {
- let mut bytes = redstone_marker_bytes();
- let rest = bytes.trim_end(size);
- (bytes, rest)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -
pub trait TrimZeros {
- fn trim_zeros(self) -> Self;
-}
-
-impl TrimZeros for Vec<u8> {
- fn trim_zeros(self) -> Self {
- let mut res = self.len();
-
- for i in (0..self.len()).rev() {
- if self[i] != 0 {
- break;
- }
-
- res = i;
- }
-
- let (rest, _) = self.split_at(res);
-
- rest.into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{protocol::constants::REDSTONE_MARKER, utils::trim_zeros::TrimZeros};
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.as_slice().into()
- }
-
- #[test]
- fn test_trim_zeros() {
- let trimmed = redstone_marker_bytes().trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
-
- let trimmed = trimmed.trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
- }
-
- #[test]
- fn test_trim_zeros_empty() {
- let trimmed = Vec::<u8>::default().trim_zeros();
- assert_eq!(trimmed, Vec::<u8>::default());
- }
-}
-
fn:
) to \
- restrict the search to a given item kind.","Accepted kinds are: fn
, mod
, struct
, \
- enum
, trait
, type
, macro
, \
- and const
.","Search functions by type signature (e.g., vec -> usize
or \
- -> vec
or String, enum:Cow -> bool
)","You can look for items with an exact name by putting double quotes around \
- your request: \"string\"
","Look for functions that accept or return \
- slices and \
- arrays by writing \
- square brackets (e.g., -> [u8]
or [] -> Option
)","Look for items inside another one by searching for a path: vec::Vec
",].map(x=>""+x+"
").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="${value.replaceAll(" ", " ")}
`}else{error[index]=value}});output+=`Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,\nas it avoids reallocation if possible. Additionally, if the element type\nT
overrides clone_from()
, this will reuse the resources of self
’s\nelements as well.
let x = vec![5, 6, 7];\nlet mut y = vec![8, 9, 10];\nlet yp: *const i32 = y.as_ptr();\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no reallocation occurred\nassert_eq!(yp, y.as_ptr());
Extend implementation that copies elements out of references before pushing them onto the Vec.
\nThis implementation is specialized for slice iterators, where it uses copy_from_slice
to\nappend the entire slice at once.
extend_one
)extend_one
)extend_one
)extend_one
)Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has\nconstant time complexity.
\nConvert a clone-on-write slice into a vector.
\nIf s
already owns a Vec<T>
, it will be returned directly.\nIf s
is borrowing a slice, a new Vec<T>
will be allocated and\nfilled by cloning s
’s items into it.
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);\nlet b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);\nassert_eq!(Vec::from(o), Vec::from(b));
Turn a VecDeque<T>
into a Vec<T>
.
This never needs to re-allocate, but does need to do O(n) data movement if\nthe circular buffer doesn’t happen to be at the beginning of the allocation.
\nuse std::collections::VecDeque;\n\n// This one is *O*(1).\nlet deque: VecDeque<_> = (1..5).collect();\nlet ptr = deque.as_slices().0.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);\n\n// This one needs data rearranging.\nlet mut deque: VecDeque<_> = (1..5).collect();\ndeque.push_front(9);\ndeque.push_front(8);\nlet ptr = deque.as_slices().1.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [8, 9, 1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);
Collects an iterator into a Vec, commonly called via Iterator::collect()
In general Vec
does not guarantee any particular growth or allocation strategy.\nThat also applies to this trait impl.
Note: This section covers implementation details and is therefore exempt from\nstability guarantees.
\nVec may use any or none of the following strategies,\ndepending on the supplied iterator:
\nIterator::size_hint()
\npushing
one item at a timeThe last case warrants some attention. It is an optimization that in many cases reduces peak memory\nconsumption and improves cache locality. But when big, short-lived allocations are created,\nonly a small fraction of their items get collected, no further use is made of the spare capacity\nand the resulting Vec
is moved into a longer-lived structure, then this can lead to the large\nallocations having their lifetimes unnecessarily extended which can result in increased memory\nfootprint.
In cases where this is an issue, the excess capacity can be discarded with Vec::shrink_to()
,\nVec::shrink_to_fit()
or by collecting into Box<[T]>
instead, which additionally reduces\nthe size of the long-lived struct.
static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());\n\nfor i in 0..10 {\n let big_temporary: Vec<u16> = (0..1024).collect();\n // discard most items\n let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();\n // without this a lot of unused capacity might be moved into the global\n result.shrink_to_fit();\n LONG_LIVED.lock().unwrap().push(result);\n}
The hash of a vector is the same as that of the corresponding slice,\nas required by the core::borrow::Borrow
implementation.
use std::hash::BuildHasher;\n\nlet b = std::hash::RandomState::new();\nlet v: Vec<u8> = vec![0xa8, 0x3c, 0x09];\nlet s: &[u8] = &[0xa8, 0x3c, 0x09];\nassert_eq!(b.hash_one(v), b.hash_one(s));
Creates a consuming iterator, that is, one that moves each value out of\nthe vector (from start to end). The vector cannot be used after calling\nthis.
\nlet v = vec![\"a\".to_string(), \"b\".to_string()];\nlet mut v_iter = v.into_iter();\n\nlet first_element: Option<String> = v_iter.next();\n\nassert_eq!(first_element, Some(\"a\".to_string()));\nassert_eq!(v_iter.next(), Some(\"b\".to_string()));\nassert_eq!(v_iter.next(), None);
Implements ordering of vectors, lexicographically.
\nImplements comparison of vectors, lexicographically.
\nself
and other
) and is used by the <=
\noperator. Read moreVec<u8>
which would be returned from a successful call to\nto_bytes()
or into_bytes()
. The data is not actually serialized, so this call is\nrelatively cheap.Constructs a new, empty Vec<T>
.
The vector will not allocate until elements are pushed onto it.
\nlet mut vec: Vec<i32> = Vec::new();
Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = Vec::with_capacity(10);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<()>::with_capacity(10);\nassert_eq!(vec_units.capacity(), usize::MAX);
try_with_capacity
)Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
Creates a Vec<T>
directly from a pointer, a length, and a capacity.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must have been allocated using the global allocator, such as via\nthe alloc::alloc
function.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to be the capacity that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is normally not safe\nto build a Vec<u8>
from a pointer to a C char
array with length\nsize_t
, doing so is only safe if the array was initially allocated by\na Vec
or String
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid\nthese issues, it is often preferable to do casting/transmuting using\nslice::from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
use std::ptr;\nuse std::mem;\n\nlet v = vec![1, 2, 3];\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts(p, len, cap);\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\nuse std::alloc::{alloc, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = alloc(layout).cast::<u32>();\n if mem.is_null() {\n return;\n }\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts(mem, 1, 16)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with value
.\nIf new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,\nin order to be able to clone the passed value.\nIf you need more flexibility (or want to rely on Default
instead of\nClone
), use Vec::resize_with
.\nIf you only need to resize to a smaller size, use Vec::truncate
.
let mut vec = vec![\"hello\"];\nvec.resize(3, \"world\");\nassert_eq!(vec, [\"hello\", \"world\", \"world\"]);\n\nlet mut vec = vec![1, 2, 3, 4];\nvec.resize(2, 0);\nassert_eq!(vec, [1, 2]);
Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends\nit to this Vec
. The other
slice is traversed in-order.
Note that this function is same as extend
except that it is\nspecialized to work with slices instead. If and when Rust gets\nspecialization this function will likely be deprecated (but still\navailable).
let mut vec = vec![1];\nvec.extend_from_slice(&[2, 3, 4]);\nassert_eq!(vec, [1, 2, 3, 4]);
Copies elements from src
range to the end of the vector.
Panics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut vec = vec![0, 1, 2, 3, 4];\n\nvec.extend_from_within(2..);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);\n\nvec.extend_from_within(..2);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);\n\nvec.extend_from_within(4..8);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
Creates a splicing iterator that replaces the specified range in the vector\nwith the given replace_with
iterator and yields the removed items.\nreplace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many elements are removed from the vector\nif the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
\nrange
) is empty,replace_with
yields fewer or equal elements than range
’s lengthsize_hint()
is exact.Otherwise, a temporary vector is allocated and the tail is moved twice.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut v = vec![1, 2, 3, 4];\nlet new = [7, 8, 9];\nlet u: Vec<_> = v.splice(1..3, new).collect();\nassert_eq!(v, &[1, 7, 8, 9, 4]);\nassert_eq!(u, &[2, 3]);
extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, then the element is removed and yielded.\nIf the closure returns false, the element will remain in the vector and will not be yielded\nby the iterator.
\nIf the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
\n\nlet mut i = 0;\nwhile i < vec.len() {\n if some_predicate(&mut vec[i]) {\n let val = vec.remove(i);\n // your code here\n } else {\n i += 1;\n }\n}\n
But extract_if
is easier to use. extract_if
is also more efficient,\nbecause it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate every element in the filter closure,\nregardless of whether you choose to keep or remove it.
Splitting an array into evens and odds, reusing the original allocation:
\n\n#![feature(extract_if)]\nlet mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];\n\nlet evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();\nlet odds = numbers;\n\nassert_eq!(evens, vec![2, 4, 6, 8, 14]);\nassert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
allocator_api
)Constructs a new, empty Vec<T, A>
.
The vector will not allocate until elements are pushed onto it.
\n#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec: Vec<i32, _> = Vec::new_in(System);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T, A>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec = Vec::with_capacity_in(10, System);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<(), System>::with_capacity_in(10, System);\nassert_eq!(vec_units.capacity(), usize::MAX);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
allocator_api
)Creates a Vec<T, A>
directly from a pointer, a length, a capacity,\nand an allocator.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must be currently allocated via the given allocator alloc
.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to fit the layout size that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T, A>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is not safe\nto build a Vec<u8>
from a pointer to a C char
array with length size_t
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nuse std::ptr;\nuse std::mem;\n\nlet mut v = Vec::with_capacity_in(3, System);\nv.push(1);\nv.push(2);\nv.push(3);\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\nlet alloc = v.allocator();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\n#![feature(allocator_api)]\n\nuse std::alloc::{AllocError, Allocator, Global, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = match Global.allocate(layout) {\n Ok(mem) => mem.cast::<u32>().as_ptr(),\n Err(AllocError) => return,\n };\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts_in(mem, 1, 16, Global)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
vec_into_raw_parts
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity)
.
Returns the raw pointer to the underlying data, the length of\nthe vector (in elements), and the allocated capacity of the\ndata (in elements). These are the same arguments in the same\norder as the arguments to from_raw_parts
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts
function, allowing\nthe destructor to perform the cleanup.
#![feature(vec_into_raw_parts)]\nlet v: Vec<i32> = vec![-1, 0, 1];\n\nlet (ptr, len, cap) = v.into_raw_parts();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts(ptr, len, cap)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
allocator_api
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity, allocator)
.
Returns the raw pointer to the underlying data, the length of the vector (in elements),\nthe allocated capacity of the data (in elements), and the allocator. These are the same\narguments in the same order as the arguments to from_raw_parts_in
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts_in
function, allowing\nthe destructor to perform the cleanup.
#![feature(allocator_api, vec_into_raw_parts)]\n\nuse std::alloc::System;\n\nlet mut v: Vec<i32, System> = Vec::new_in(System);\nv.push(-1);\nv.push(0);\nv.push(1);\n\nlet (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts_in(ptr, len, cap, alloc)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
Returns the total number of elements the vector can hold without\nreallocating.
\nlet mut vec: Vec<i32> = Vec::with_capacity(10);\nvec.push(42);\nassert!(vec.capacity() >= 10);
Reserves capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to\nspeculatively avoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve(10);\nassert!(vec.capacity() >= 11);
Reserves the minimum capacity for at least additional
more elements to\nbe inserted in the given Vec<T>
. Unlike reserve
, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact
, capacity will be greater than or equal to\nself.len() + additional
. Does nothing if the capacity is already\nsufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer reserve
if future insertions are expected.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve_exact(10);\nassert!(vec.capacity() >= 11);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to speculatively avoid\nfrequent reallocations. After calling try_reserve
, capacity will be\ngreater than or equal to self.len() + additional
if it returns\nOk(())
. Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Tries to reserve the minimum capacity for at least additional
\nelements to be inserted in the given Vec<T>
. Unlike try_reserve
,\nthis will not deliberately over-allocate to speculatively avoid frequent\nallocations. After calling try_reserve_exact
, capacity will be greater\nthan or equal to self.len() + additional
if it returns Ok(())
.\nDoes nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve
if future insertions are expected.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve_exact(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Shrinks the capacity of the vector as much as possible.
\nThe behavior of this method depends on the allocator, which may either shrink the vector\nin-place or reallocate. The resulting vector might still have some excess capacity, just as\nis the case for with_capacity
. See Allocator::shrink
for more details.
let mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to_fit();\nassert!(vec.capacity() >= 3);
Shrinks the capacity of the vector with a lower bound.
\nThe capacity will remain at least as large as both the length\nand the supplied value.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to(4);\nassert!(vec.capacity() >= 4);\nvec.shrink_to(0);\nassert!(vec.capacity() >= 3);
Converts the vector into Box<[T]>
.
Before doing the conversion, this method discards excess capacity like shrink_to_fit
.
let v = vec![1, 2, 3];\n\nlet slice = v.into_boxed_slice();
Any excess capacity is removed:
\n\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\n\nassert!(vec.capacity() >= 10);\nlet slice = vec.into_boxed_slice();\nassert_eq!(slice.into_vec().capacity(), 3);
Shortens the vector, keeping the first len
elements and dropping\nthe rest.
If len
is greater or equal to the vector’s current length, this has\nno effect.
The drain
method can emulate truncate
, but causes the excess\nelements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity\nof the vector.
\nTruncating a five element vector to two elements:
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nvec.truncate(2);\nassert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current\nlength:
let mut vec = vec![1, 2, 3];\nvec.truncate(8);\nassert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
\nmethod.
let mut vec = vec![1, 2, 3];\nvec.truncate(0);\nassert_eq!(vec, []);
Extracts a slice containing the entire vector.
\nEquivalent to &s[..]
.
use std::io::{self, Write};\nlet buffer = vec![1, 2, 3, 5, 8];\nio::sink().write(buffer.as_slice()).unwrap();
Extracts a mutable slice of the entire vector.
\nEquivalent to &mut s[..]
.
use std::io::{self, Read};\nlet mut buffer = vec![0; 3];\nio::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer\nvalid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThe caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell
) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize mutable references to the slice,\nor mutable references to specific elements you are planning on accessing through this pointer,\nas well as writing to those elements, may still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
let x = vec![1, 2, 4];\nlet x_ptr = x.as_ptr();\n\nunsafe {\n for i in 0..x.len() {\n assert_eq!(*x_ptr.add(i), 1 << i);\n }\n}
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0, 1, 2];\n let ptr1 = v.as_ptr();\n let _ = ptr1.read();\n let ptr2 = v.as_mut_ptr().offset(2);\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`\n // because it mutated a different element:\n let _ = ptr1.read();\n}
Returns an unsafe mutable pointer to the vector’s buffer, or a dangling\nraw pointer valid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThis method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize references to the slice,\nor references to specific elements you are planning on accessing through this pointer,\nmay still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
// Allocate vector big enough for 4 elements.\nlet size = 4;\nlet mut x: Vec<i32> = Vec::with_capacity(size);\nlet x_ptr = x.as_mut_ptr();\n\n// Initialize elements via raw pointer writes, then set length.\nunsafe {\n for i in 0..size {\n *x_ptr.add(i) = i as i32;\n }\n x.set_len(size);\n}\nassert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0];\n let ptr1 = v.as_mut_ptr();\n ptr1.write(1);\n let ptr2 = v.as_mut_ptr();\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`:\n ptr1.write(3);\n}
allocator_api
)Returns a reference to the underlying allocator.
\nForces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal\ninvariants of the type. Normally changing the length of a vector\nis done using one of the safe operations instead, such as\ntruncate
, resize
, extend
, or clear
.
new_len
must be less than or equal to capacity()
.old_len..new_len
must be initialized.This method can be useful for situations in which the vector\nis serving as a buffer for other code, particularly over FFI:
\n\npub fn get_dictionary(&self) -> Option<Vec<u8>> {\n // Per the FFI method's docs, \"32768 bytes is always enough\".\n let mut dict = Vec::with_capacity(32_768);\n let mut dict_length = 0;\n // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:\n // 1. `dict_length` elements were initialized.\n // 2. `dict_length` <= the capacity (32_768)\n // which makes `set_len` safe to call.\n unsafe {\n // Make the FFI call...\n let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);\n if r == Z_OK {\n // ...and update the length to what was initialized.\n dict.set_len(dict_length);\n Some(dict)\n } else {\n None\n }\n }\n}
While the following example is sound, there is a memory leak since\nthe inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],\n vec![0, 1, 0],\n vec![0, 0, 1]];\n// SAFETY:\n// 1. `old_len..0` is empty so no elements need to be initialized.\n// 2. `0 <= capacity` always holds whatever `capacity` is.\nunsafe {\n vec.set_len(0);\n}
Normally, here, one would use clear
instead to correctly drop\nthe contents and thus not leak memory.
Removes an element from the vector and returns it.
\nThe removed element is replaced by the last element of the vector.
\nThis does not preserve ordering of the remaining elements, but is O(1).\nIf you need to preserve the element order, use remove
instead.
Panics if index
is out of bounds.
let mut v = vec![\"foo\", \"bar\", \"baz\", \"qux\"];\n\nassert_eq!(v.swap_remove(1), \"bar\");\nassert_eq!(v, [\"foo\", \"qux\", \"baz\"]);\n\nassert_eq!(v.swap_remove(0), \"foo\");\nassert_eq!(v, [\"baz\", \"qux\"]);
Inserts an element at position index
within the vector, shifting all\nelements after it to the right.
Panics if index > len
.
let mut vec = vec![1, 2, 3];\nvec.insert(1, 4);\nassert_eq!(vec, [1, 4, 2, 3]);\nvec.insert(4, 5);\nassert_eq!(vec, [1, 4, 2, 3, 5]);
Takes O(Vec::len
) time. All items after the insertion index must be\nshifted to the right. In the worst case, all elements are shifted when\nthe insertion index is 0.
Removes and returns the element at position index
within the vector,\nshifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a\nworst-case performance of O(n). If you don’t need the order of elements\nto be preserved, use swap_remove
instead. If you’d like to remove\nelements from the beginning of the Vec
, consider using\nVecDeque::pop_front
instead.
Panics if index
is out of bounds.
let mut v = vec![1, 2, 3];\nassert_eq!(v.remove(1), 2);\nassert_eq!(v, [1, 3]);
Retains only the elements specified by the predicate.
\nIn other words, remove all elements e
for which f(&e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain(|&x| x % 2 == 0);\nassert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\nvec.retain(|_| *iter.next().unwrap());\nassert_eq!(vec, [2, 3, 5]);
Retains only the elements specified by the predicate, passing a mutable reference to it.
\nIn other words, remove all elements e
such that f(&mut e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain_mut(|x| if *x <= 3 {\n *x += 1;\n true\n} else {\n false\n});\nassert_eq!(vec, [2, 3, 4]);
Removes all but the first of consecutive elements in the vector that resolve to the same\nkey.
\nIf the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![10, 20, 21, 30, 20];\n\nvec.dedup_by_key(|i| *i / 10);\n\nassert_eq!(vec, [10, 20, 30, 20]);
Removes all but the first of consecutive elements in the vector satisfying a given equality\nrelation.
\nThe same_bucket
function is passed references to two elements from the vector and\nmust determine if the elements compare equal. The elements are passed in opposite order\nfrom their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![\"foo\", \"bar\", \"Bar\", \"baz\", \"bar\"];\n\nvec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));\n\nassert_eq!(vec, [\"foo\", \"bar\", \"baz\", \"bar\"]);
Appends an element to the back of a collection.
\nPanics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1, 2];\nvec.push(3);\nassert_eq!(vec, [1, 2, 3]);
Takes amortized O(1) time. If the vector’s length would exceed its\ncapacity after the push, O(capacity) time is taken to copy the\nvector’s elements to a larger allocation. This expensive operation is\noffset by the capacity O(1) insertions it allows.
\nvec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned\nwith the element.
\nUnlike push
this method will not reallocate when there’s insufficient capacity.\nThe caller should use reserve
or try_reserve
to ensure that there is enough capacity.
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]\n\nuse std::collections::TryReserveError;\nfn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {\n let mut vec = Vec::new();\n for value in iter {\n if let Err(value) = vec.push_within_capacity(value) {\n vec.try_reserve(1)?;\n // this cannot fail, the previous line either returned or added at least 1 free slot\n let _ = vec.push_within_capacity(value);\n }\n }\n Ok(vec)\n}\nassert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
Takes O(1) time.
\nRemoves the last element from a vector and returns it, or None
if it\nis empty.
If you’d like to pop the first element, consider using\nVecDeque::pop_front
instead.
let mut vec = vec![1, 2, 3];\nassert_eq!(vec.pop(), Some(3));\nassert_eq!(vec, [1, 2]);
Takes O(1) time.
\nvec_pop_if
)Removes and returns the last element in a vector if the predicate\nreturns true
, or None
if the predicate returns false or the vector\nis empty.
#![feature(vec_pop_if)]\n\nlet mut vec = vec![1, 2, 3, 4];\nlet pred = |x: &mut i32| *x % 2 == 0;\n\nassert_eq!(vec.pop_if(pred), Some(4));\nassert_eq!(vec, [1, 2, 3]);\nassert_eq!(vec.pop_if(pred), None);
Removes the specified range from the vector in bulk, returning all\nremoved elements as an iterator. If the iterator is dropped before\nbeing fully consumed, it drops the remaining removed elements.
\nThe returned iterator keeps a mutable borrow on the vector to optimize\nits implementation.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nIf the returned iterator goes out of scope without being dropped (due to\nmem::forget
, for example), the vector may have lost and leaked\nelements arbitrarily, including elements outside the range.
let mut v = vec![1, 2, 3];\nlet u: Vec<_> = v.drain(1..).collect();\nassert_eq!(v, &[1]);\nassert_eq!(u, &[2, 3]);\n\n// A full range clears the vector, like `clear()` does\nv.drain(..);\nassert_eq!(v, &[]);
Clears the vector, removing all values.
\nNote that this method has no effect on the allocated capacity\nof the vector.
\nlet mut v = vec![1, 2, 3];\n\nv.clear();\n\nassert!(v.is_empty());
Returns the number of elements in the vector, also referred to\nas its ‘length’.
\nlet a = vec![1, 2, 3];\nassert_eq!(a.len(), 3);
Returns true
if the vector contains no elements.
let mut v = Vec::new();\nassert!(v.is_empty());\n\nv.push(1);\nassert!(!v.is_empty());
Splits the collection into two at the given index.
\nReturns a newly allocated vector containing the elements in the range\n[at, len)
. After the call, the original vector will be left containing\nthe elements [0, at)
with its previous capacity unchanged.
mem::take
or mem::replace
.Vec::truncate
.Vec::drain
.Panics if at > len
.
let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with the result of\ncalling the closure f
. The return values from f
will end up\nin the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If\nyou’d rather Clone
a given value, use Vec::resize
. If you\nwant to use the Default
trait to generate values, you can\npass Default::default
as the second argument.
let mut vec = vec![1, 2, 3];\nvec.resize_with(5, Default::default);\nassert_eq!(vec, [1, 2, 3, 0, 0]);\n\nlet mut vec = vec![];\nlet mut p = 1;\nvec.resize_with(4, || { p *= 2; p });\nassert_eq!(vec, [2, 4, 8, 16]);
Consumes and leaks the Vec
, returning a mutable reference to the contents,\n&'a mut [T]
. Note that the type T
must outlive the chosen lifetime\n'a
. If the type has only static references, or none at all, then this\nmay be chosen to be 'static
.
As of Rust 1.57, this method does not reallocate or shrink the Vec
,\nso the leaked allocation may include unused capacity that is not part\nof the returned slice.
This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak.
\nSimple usage:
\n\nlet x = vec![1, 2, 3];\nlet static_ref: &'static mut [usize] = x.leak();\nstatic_ref[0] += 1;\nassert_eq!(static_ref, &[2, 2, 3]);
Returns the remaining spare capacity of the vector as a slice of\nMaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by\nreading from a file) before marking the data as initialized using the\nset_len
method.
// Allocate vector big enough for 10 elements.\nlet mut v = Vec::with_capacity(10);\n\n// Fill in the first 3 elements.\nlet uninit = v.spare_capacity_mut();\nuninit[0].write(0);\nuninit[1].write(1);\nuninit[2].write(2);\n\n// Mark the first 3 elements of the vector as being initialized.\nunsafe {\n v.set_len(3);\n}\n\nassert_eq!(&v, &[0, 1, 2]);
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare\ncapacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data\n(e.g. by reading from a file) before marking the data as initialized using\nthe set_len
method.
Note that this is a low-level API, which should be used with care for\noptimization purposes. If you need to append data to a Vec
\nyou can use push
, extend
, extend_from_slice
,\nextend_from_within
, insert
, append
, resize
or\nresize_with
, depending on your exact needs.
#![feature(vec_split_at_spare)]\n\nlet mut v = vec![1, 1, 2];\n\n// Reserve additional space big enough for 10 elements.\nv.reserve(10);\n\nlet (init, uninit) = v.split_at_spare_mut();\nlet sum = init.iter().copied().sum::<u32>();\n\n// Fill in the next 4 elements.\nuninit[0].write(sum);\nuninit[1].write(sum * 2);\nuninit[2].write(sum * 3);\nuninit[3].write(sum * 4);\n\n// Mark the 4 elements of the vector as being initialized.\nunsafe {\n let len = v.len();\n v.set_len(len + 4);\n}\n\nassert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
pub(crate) fn aggregate_values(
- config: Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<U256>
Aggregates values from a collection of data packages according to the provided configuration.
-This function takes a configuration and a vector of data packages, constructs a matrix of values
-and their corresponding signers, and then aggregates these values based on the aggregation logic
-defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-an average of the values, selecting the median, or applying a custom algorithm defined within the
-aggregate_matrix
function.
The primary purpose of this function is to consolidate data from multiple sources into a coherent
-and singular value set that adheres to the criteria specified in the Config
.
config
- A Config
instance containing settings and parameters used to guide the aggregation process.data_packages
- A vector of DataPackage
instances, each representing a set of values and associated
-metadata collected from various sources or signers.Returns a Vec<U256>
, which is a vector of aggregated values resulting from applying the aggregation
-logic to the input data packages as per the specified configuration. Each U256
value in the vector
-represents an aggregated result derived from the corresponding data packages.
This function is internal to the crate (pub(crate)
) and not exposed as part of the public API. It is
-designed to be used by other components within the same crate that require value aggregation functionality.
fn make_value_signer_matrix(
- config: &Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<Vec<Option<U256>>>
pub struct Config {
- pub signer_count_threshold: u8,
- pub signers: Vec<Bytes>,
- pub feed_ids: Vec<U256>,
- pub block_timestamp: u64,
-}
Configuration for a RedStone payload processor.
-Specifies the parameters necessary for the verification and aggregation of values -from various data points passed by the RedStone payload.
-signer_count_threshold: u8
The minimum number of signers required validating the data.
-Specifies how many unique signers (from different addresses) are required -for the data to be considered valid and trustworthy.
-signers: Vec<Bytes>
List of identifiers for signers authorized to sign the data.
-Each signer is identified by a unique, network-specific byte string (Bytes
),
-which represents their address.
feed_ids: Vec<U256>
Identifiers for the data feeds from which values are aggregated.
-Each data feed id is represented by the network-specific U256
type.
block_timestamp: u64
The current block time in timestamp format, used for verifying data timeliness.
-The value’s been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows -for determining whether the data is current in the context of blockchain time.
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult
pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult
The main processor of the RedStone payload.
-config
- Configuration of the payload processing.payload_bytes
- Network-specific byte-list of the payload to be processed.pub struct ProcessorResult {
- pub min_timestamp: u64,
- pub values: Vec<U256>,
-}
Represents the result of processing the RedStone payload.
-This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-particularly focusing on time-sensitive data and its associated values, according to the Config
.
min_timestamp: u64
The minimum timestamp encountered during processing.
-This field captures the earliest time point (in milliseconds since the Unix epoch) -among the processed data packages, indicating the starting boundary of the dataset’s time range.
-values: Vec<U256>
A collection of values processed during the operation.
-Each element in this vector represents a processed value corresponding
-to the passed data_feed item in the Config
.
self
and other
values to be equal, and is used
-by ==
.pub(crate) trait Validator {
- // Required methods
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
- fn validate_signer_count_threshold(
- &self,
- index: usize,
- values: &[Option<U256>],
- ) -> Vec<U256>;
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
A trait defining validation operations for data feeds and signers.
-This trait specifies methods for validating aspects of data feeds and signers within a system that -requires data integrity and authenticity checks. Implementations of this trait are responsible for -defining the logic behind each validation step, ensuring that data conforms to expected rules and -conditions.
-Retrieves the index of a given data feed.
-This method takes a feed_id
representing the unique identifier of a data feed and
-returns an Option<usize>
indicating the index of the feed within a collection of feeds.
-If the feed does not exist, None
is returned.
feed_id
: U256
- The unique identifier of the data feed.Option<usize>
- The index of the feed if it exists, or None
if it does not.Retrieves the index of a given signer.
-This method accepts a signer identifier in the form of a byte slice and returns an
-Option<usize>
indicating the signer’s index within a collection of signers. If the signer
-is not found, None
is returned.
signer
: &[u8]
- A byte slice representing the signer’s identifier.Option<usize>
- The index of the signer if found, or None
if not found.Validates the signer count threshold for a given index within a set of values.
-This method is responsible for ensuring that the number of valid signers meets or exceeds
-a specified threshold necessary for a set of data values to be considered valid. It returns
-a vector of U256
if the values pass the validation, to be processed in other steps.
index
: usize
- The index of the data value being validated.values
: &[Option<U256>]
- A slice of optional U256
values associated with the data.Vec<U256>
- A vector of U256
values that meet the validation criteria.Validates the timestamp for a given index.
-This method checks whether a timestamp associated with a data value at a given index -meets specific conditions (e.g., being within an acceptable time range). It returns -the validated timestamp if it’s valid, to be processed in other steps.
-index
: usize
- The index of the data value whose timestamp is being validated.timestamp
: u64
- The timestamp to be validated.u64
- The validated timestamp.redstone
is a collection of utilities to make deserializing&decrypting RedStone payload.
-It includes a pure Rust implementation, along with extensions for certain networks.
Different crypto-mechanisms are easily injectable.
-The current implementation contains secp256k1
- and k256
-based variants.
Redirecting to macro.print_and_panic.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_and_panic.html b/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_and_panic.html deleted file mode 100644 index b308eb68..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_and_panic.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_and_panic { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
Redirecting to macro.print_debug.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_debug.html b/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_debug.html deleted file mode 100644 index 3cb863d6..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_casper/redstone/macro.print_debug.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_debug { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
pub trait AsAsciiStr {
- // Required method
- fn as_ascii_str(&self) -> String;
-}
pub trait AsHexStr {
- // Required method
- fn as_hex_str(&self) -> String;
-}
pub trait Assert<F> {
- // Required method
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
pub trait Unwrap<R> {
- type ErrorArg;
-
- // Required method
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
pub struct Casper;
pub enum Error {
- ContractError(Box<dyn ContractErrorContent>),
- NumberOverflow(U256),
- ArrayIsEmpty,
- CryptographicError(usize),
- SizeNotSupported(usize),
- WrongRedStoneMarker(Vec<u8>),
- NonEmptyPayloadRemainder(Vec<u8>),
- InsufficientSignerCount(usize, usize, U256),
- TimestampTooOld(usize, u64),
- TimestampTooFuture(usize, u64),
- ClonedContractError(u8, String),
-}
Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-These errors include issues with contract logic, data types, -cryptographic operations, and conditions specific to the requirements.
-Represents errors that arise from the contract itself.
-This variant is used for encapsulating errors that are specific to the contract’s logic -or execution conditions that aren’t covered by more specific error types.
-Indicates an overflow error with U256
numbers.
Used when operations on U256
numbers exceed their maximum value, potentially leading
-to incorrect calculations or state.
Used when an expected non-empty array or vector is found to be empty.
-This could occur in scenarios where the contract logic requires a non-empty collection -of items for the correct operation, for example, during aggregating the values.
-Represents errors related to cryptographic operations.
-This includes failures in signature verification, hashing, or other cryptographic -processes, with the usize indicating the position or identifier of the failed operation.
-Signifies that an unsupported size was encountered.
-This could be used when a data structure or input does not meet the expected size -requirements for processing.
-Indicates that the marker bytes for RedStone are incorrect.
-This error is specific to scenarios where marker or identifier bytes do not match -expected values, potentially indicating corrupted or tampered data.
-Used when there is leftover data in a payload that should have been empty.
-This could indicate an error in data parsing or that additional, unexpected data -was included in a message or transaction.
-Indicates that the number of signers does not meet the required threshold.
-This variant includes the current number of signers, the required threshold, and -potentially a feed_id related to the operation that failed due to insufficient signers.
-Used when a timestamp is older than allowed by the processor logic.
-Includes the position or identifier of the timestamp and the threshold value, -indicating that the provided timestamp is too far in the past.
-Indicates that a timestamp is further in the future than allowed.
-Similar to TimestampTooOld
, but for future timestamps exceeding the contract’s
-acceptance window.
Represents errors that need to clone ContractErrorContent
, which is not supported by default.
This variant allows for the manual duplication of contract error information, including -an error code and a descriptive message.
-pub trait FromBytesRepr<T> {
- // Required method
- fn from_bytes_repr(bytes: T) -> Self;
-}
pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- // Required methods
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage
pub(crate) fn trim_data_packages(
- payload: &mut Vec<u8>,
- count: usize,
-) -> Vec<DataPackage>
pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
signer_address: Vec<u8>
§timestamp: u64
§data_points: Vec<DataPoint>
source
. Read moreself
and other
values to be equal, and is used
-by ==
.fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint
pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
feed_id: U256
§value: U256
pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
data_packages: Vec<DataPackage>
pub(crate) trait FilterSome<Output> {
- // Required method
- fn filter_some(&self) -> Output;
-}
fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>where
- T: PartialOrd,
trait Averageable: Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy { }
pub trait TrimZeros {
- // Required method
- fn trim_zeros(self) -> Self;
-}
U::from(self)
.\nThe minimum number of signers required validating the data.\nList of identifiers for signers authorized to sign the …\nThe main processor of the RedStone payload.\nRepresents the result of processing the RedStone payload.\nReturns the argument unchanged.\nCalls U::from(self)
.\nThe minimum timestamp encountered during processing.\nA collection of values processed during the operation.\nA trait defining validation operations for data feeds and …\nRetrieves the index of a given data feed.\nRetrieves the index of a given signer.\nValidates the signer count threshold for a given index …\nValidates the timestamp for a given index.\nReturns the argument unchanged.\nCalls U::from(self)
.\nUsed when an expected non-empty array or vector is found …\nRepresents errors that need to clone ContractErrorContent
, …\nRepresents errors that arise from the contract itself.\nRepresents errors related to cryptographic operations.\nErrors that can be encountered in the …\nIndicates that the number of signers does not meet the …\nUsed when there is leftover data in a payload that should …\nIndicates an overflow error with U256
numbers.\nSignifies that an unsupported size was encountered.\nIndicates that a timestamp is further in the future than …\nUsed when a timestamp is older than allowed by the …\nIndicates that the marker bytes for RedStone are incorrect.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.")
\ No newline at end of file
diff --git a/static/rust/redstone/crypto_secp256k1,network_casper/settings.html b/static/rust/redstone/crypto_secp256k1,network_casper/settings.html
deleted file mode 100644
index 9631dcb2..00000000
--- a/static/rust/redstone/crypto_secp256k1,network_casper/settings.html
+++ /dev/null
@@ -1 +0,0 @@
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -
use crate::{
- core::{config::Config, validator::Validator},
- network::specific::U256,
- print_debug,
- protocol::data_package::DataPackage,
- utils::median::Median,
-};
-
-type Matrix = Vec<Vec<Option<U256>>>;
-
-/// Aggregates values from a collection of data packages according to the provided configuration.
-///
-/// This function takes a configuration and a vector of data packages, constructs a matrix of values
-/// and their corresponding signers, and then aggregates these values based on the aggregation logic
-/// defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-/// an average of the values, selecting the median, or applying a custom algorithm defined within the
-/// `aggregate_matrix` function.
-///
-/// The primary purpose of this function is to consolidate data from multiple sources into a coherent
-/// and singular value set that adheres to the criteria specified in the `Config`.
-///
-/// # Arguments
-///
-/// * `config` - A `Config` instance containing settings and parameters used to guide the aggregation process.
-/// * `data_packages` - A vector of `DataPackage` instances, each representing a set of values and associated
-/// metadata collected from various sources or signers.
-///
-/// # Returns
-///
-/// Returns a `Vec<U256>`, which is a vector of aggregated values resulting from applying the aggregation
-/// logic to the input data packages as per the specified configuration. Each `U256` value in the vector
-/// represents an aggregated result derived from the corresponding data packages.
-///
-/// # Note
-///
-/// This function is internal to the crate (`pub(crate)`) and not exposed as part of the public API. It is
-/// designed to be used by other components within the same crate that require value aggregation functionality.
-pub(crate) fn aggregate_values(config: Config, data_packages: Vec<DataPackage>) -> Vec<U256> {
- aggregate_matrix(make_value_signer_matrix(&config, data_packages), config)
-}
-
-fn aggregate_matrix(matrix: Matrix, config: Config) -> Vec<U256> {
- matrix
- .iter()
- .enumerate()
- .map(|(index, values)| {
- config
- .validate_signer_count_threshold(index, values)
- .median()
- })
- .collect()
-}
-
-fn make_value_signer_matrix(config: &Config, data_packages: Vec<DataPackage>) -> Matrix {
- let mut matrix = vec![vec![None; config.signers.len()]; config.feed_ids.len()];
-
- data_packages.iter().for_each(|data_package| {
- if let Some(signer_index) = config.signer_index(&data_package.signer_address) {
- data_package.data_points.iter().for_each(|data_point| {
- if let Some(feed_index) = config.feed_index(data_point.feed_id) {
- matrix[feed_index][signer_index] = data_point.value.into()
- }
- })
- }
- });
-
- print_debug!("{:?}", matrix);
-
- matrix
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod aggregate_matrix_tests {
- use crate::{
- core::{aggregator::aggregate_matrix, config::Config},
- helpers::iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- };
-
- #[test]
- fn test_aggregate_matrix() {
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8, 23].iter_into_opt(),
- ];
-
- for signer_count_threshold in 0..Config::test().signers.len() + 1 {
- let mut config = Config::test();
- config.signer_count_threshold = signer_count_threshold as u8;
-
- let result = aggregate_matrix(matrix.clone(), config);
-
- assert_eq!(result, vec![12u8, 22].iter_into());
- }
- }
-
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_one_value() {
- let mut config = Config::test();
- config.signer_count_threshold = 1;
-
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8.into(), None].opt_iter_into_opt(),
- ];
-
- let result = aggregate_matrix(matrix, config);
-
- assert_eq!(result, vec![12u8, 21].iter_into());
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_whole_feed() {
- let mut config = Config::test();
- config.signer_count_threshold = 0;
-
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, config);
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #0 (ETH)")]
- #[test]
- fn test_aggregate_matrix_missing_one_value() {
- let matrix = vec![
- vec![21u8.into(), None].opt_iter_into_opt(),
- vec![11u8, 12].iter_into_opt(),
- ];
-
- aggregate_matrix(matrix, Config::test());
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #1 (BTC)")]
- #[test]
- fn test_aggregate_matrix_missing_whole_feed() {
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, Config::test());
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod make_value_signer_matrix {
- use crate::{
- core::{
- aggregator::{make_value_signer_matrix, Matrix},
- config::Config,
- test_helpers::{AVAX, BTC, ETH, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2},
- },
- helpers::iter_into::IterInto,
- network::specific::U256,
- protocol::data_package::DataPackage,
- };
-
- #[test]
- fn test_make_value_signer_matrix_empty() {
- let config = Config::test();
-
- test_make_value_signer_matrix_of(
- vec![],
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_exact() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_greater() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_smaller() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_diagonal() {
- let data_packages = vec![
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11.into(), None], vec![None, 22.into()]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_repetitions() {
- let data_packages = vec![
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 202, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 101, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![101, 12].iter_into(), vec![21, 202].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_all_wrong() {
- let config = Config::test();
-
- let data_packages = vec![
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_mix() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- fn test_make_value_signer_matrix_of(
- data_packages: Vec<DataPackage>,
- expected_values: Vec<Vec<Option<u128>>>,
- ) {
- let config = &Config::test();
- let result = make_value_signer_matrix(config, data_packages);
-
- let expected_matrix: Matrix = expected_values
- .iter()
- .map(|row| {
- (row.iter()
- .map(|&value| value.map(U256::from))
- .collect::<Vec<_>>())
- .iter_into() as Vec<Option<U256>>
- })
- .collect();
-
- assert_eq!(result, expected_matrix)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -
use crate::network::specific::{Bytes, U256};
-
-/// Configuration for a RedStone payload processor.
-///
-/// Specifies the parameters necessary for the verification and aggregation of values
-/// from various data points passed by the RedStone payload.
-#[derive(Debug)]
-pub struct Config {
- /// The minimum number of signers required validating the data.
- ///
- /// Specifies how many unique signers (from different addresses) are required
- /// for the data to be considered valid and trustworthy.
- pub signer_count_threshold: u8,
-
- /// List of identifiers for signers authorized to sign the data.
- ///
- /// Each signer is identified by a unique, network-specific byte string (`Bytes`),
- /// which represents their address.
- pub signers: Vec<Bytes>,
-
- /// Identifiers for the data feeds from which values are aggregated.
- ///
- /// Each data feed id is represented by the network-specific `U256` type.
- pub feed_ids: Vec<U256>,
-
- /// The current block time in timestamp format, used for verifying data timeliness.
- ///
- /// The value's been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows
- /// for determining whether the data is current in the context of blockchain time.
- pub block_timestamp: u64,
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -
use crate::{
- core::{
- aggregator::aggregate_values, config::Config, processor_result::ProcessorResult,
- validator::Validator,
- },
- network::specific::Bytes,
- print_debug,
- protocol::payload::Payload,
-};
-
-/// The main processor of the RedStone payload.
-///
-///
-/// # Arguments
-///
-/// * `config` - Configuration of the payload processing.
-/// * `payload_bytes` - Network-specific byte-list of the payload to be processed.
-pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult {
- #[allow(clippy::useless_conversion)]
- let mut bytes: Vec<u8> = payload_bytes.into();
- let payload = Payload::make(&mut bytes);
- print_debug!("{:?}", payload);
-
- make_processor_result(config, payload)
-}
-
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult {
- let min_timestamp = payload
- .data_packages
- .iter()
- .enumerate()
- .map(|(index, dp)| config.validate_timestamp(index, dp.timestamp))
- .min()
- .unwrap();
-
- let values = aggregate_values(config, payload.data_packages);
-
- print_debug!("{} {:?}", min_timestamp, values);
-
- ProcessorResult {
- values,
- min_timestamp,
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- processor::make_processor_result,
- processor_result::ProcessorResult,
- test_helpers::{
- BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- },
- helpers::iter_into::IterInto,
- protocol::{data_package::DataPackage, payload::Payload},
- };
-
- #[test]
- fn test_make_processor_result() {
- let data_packages = vec![
- DataPackage::test(
- ETH,
- 11,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 5).into(),
- ),
- DataPackage::test(
- ETH,
- 13,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP + 3).into(),
- ),
- DataPackage::test(
- BTC,
- 32,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP - 2).into(),
- ),
- DataPackage::test(
- BTC,
- 31,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 400).into(),
- ),
- ];
-
- let result = make_processor_result(Config::test(), Payload { data_packages });
-
- assert_eq!(
- result,
- ProcessorResult {
- min_timestamp: TEST_BLOCK_TIMESTAMP - 2,
- values: vec![12u8, 31].iter_into()
- }
- );
- }
-}
-
use crate::network::specific::U256;
-
-/// Represents the result of processing the RedStone payload.
-///
-/// This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-/// particularly focusing on time-sensitive data and its associated values, according to the `Config`.
-#[derive(Debug, Eq, PartialEq)]
-pub struct ProcessorResult {
- /// The minimum timestamp encountered during processing.
- ///
- /// This field captures the earliest time point (in milliseconds since the Unix epoch)
- /// among the processed data packages, indicating the starting boundary of the dataset's time range.
- pub min_timestamp: u64,
-
- /// A collection of values processed during the operation.
- ///
- /// Each element in this vector represents a processed value corresponding
- /// to the passed data_feed item in the `Config`.
- pub values: Vec<U256>,
-}
-
-impl From<ProcessorResult> for (u64, Vec<U256>) {
- fn from(result: ProcessorResult) -> Self {
- (result.min_timestamp, result.values)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -
use crate::{
- core::config::Config,
- network::{
- assert::Assert,
- error::Error::{InsufficientSignerCount, TimestampTooFuture, TimestampTooOld},
- specific::U256,
- },
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- utils::filter::FilterSome,
-};
-
-/// A trait defining validation operations for data feeds and signers.
-///
-/// This trait specifies methods for validating aspects of data feeds and signers within a system that
-/// requires data integrity and authenticity checks. Implementations of this trait are responsible for
-/// defining the logic behind each validation step, ensuring that data conforms to expected rules and
-/// conditions.
-pub(crate) trait Validator {
- /// Retrieves the index of a given data feed.
- ///
- /// This method takes a `feed_id` representing the unique identifier of a data feed and
- /// returns an `Option<usize>` indicating the index of the feed within a collection of feeds.
- /// If the feed does not exist, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `feed_id`: `U256` - The unique identifier of the data feed.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the feed if it exists, or `None` if it does not.
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
-
- /// Retrieves the index of a given signer.
- ///
- /// This method accepts a signer identifier in the form of a byte slice and returns an
- /// `Option<usize>` indicating the signer's index within a collection of signers. If the signer
- /// is not found, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `signer`: `&[u8]` - A byte slice representing the signer's identifier.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the signer if found, or `None` if not found.
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
-
- /// Validates the signer count threshold for a given index within a set of values.
- ///
- /// This method is responsible for ensuring that the number of valid signers meets or exceeds
- /// a specified threshold necessary for a set of data values to be considered valid. It returns
- /// a vector of `U256` if the values pass the validation, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value being validated.
- /// * `values`: `&[Option<U256>]` - A slice of optional `U256` values associated with the data.
- ///
- /// # Returns
- ///
- /// * `Vec<U256>` - A vector of `U256` values that meet the validation criteria.
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256>;
-
- /// Validates the timestamp for a given index.
- ///
- /// This method checks whether a timestamp associated with a data value at a given index
- /// meets specific conditions (e.g., being within an acceptable time range). It returns
- /// the validated timestamp if it's valid, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value whose timestamp is being validated.
- /// * `timestamp`: `u64` - The timestamp to be validated.
- ///
- /// # Returns
- ///
- /// * `u64` - The validated timestamp.
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
-
-impl Validator for Config {
- #[inline]
- fn feed_index(&self, feed_id: U256) -> Option<usize> {
- self.feed_ids.iter().position(|&elt| elt == feed_id)
- }
-
- #[inline]
- fn signer_index(&self, signer: &[u8]) -> Option<usize> {
- self.signers
- .iter()
- .position(|elt| elt.to_ascii_lowercase() == signer.to_ascii_lowercase())
- }
-
- #[inline]
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256> {
- values.filter_some().assert_or_revert(
- |x| (*x).len() >= self.signer_count_threshold.into(),
- #[allow(clippy::useless_conversion)]
- |val| InsufficientSignerCount(index, val.len(), self.feed_ids[index]),
- )
- }
-
- #[inline]
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64 {
- timestamp.assert_or_revert(
- |&x| x + MAX_TIMESTAMP_DELAY_MS >= self.block_timestamp,
- |timestamp| TimestampTooOld(index, *timestamp),
- );
-
- timestamp.assert_or_revert(
- |&x| x <= self.block_timestamp + MAX_TIMESTAMP_AHEAD_MS,
- |timestamp| TimestampTooFuture(index, *timestamp),
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- test_helpers::{
- AVAX, BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- validator::Validator,
- },
- helpers::{
- hex::{hex_to_bytes, make_feed_id},
- iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- },
- network::specific::U256,
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- };
- use itertools::Itertools;
-
- #[test]
- fn test_feed_index() {
- let config = Config::test();
-
- let eth_index = config.feed_index(make_feed_id(ETH));
- assert_eq!(eth_index, 0.into());
-
- let eth_index = config.feed_index(make_feed_id("778680")); //eth
- assert_eq!(eth_index, None);
-
- let btc_index = config.feed_index(make_feed_id(BTC));
- assert_eq!(btc_index, 1.into());
-
- let avax_index = config.feed_index(make_feed_id(AVAX));
- assert_eq!(avax_index, None);
- }
-
- #[test]
- fn test_signer_index() {
- let config = Config::test();
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.into()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.to_uppercase()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.into()));
- assert_eq!(index, 1.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.replace('0', "1")));
- assert_eq!(index, None);
- }
-
- #[test]
- fn test_validate_timestamp() {
- let config = Config::test();
-
- config.validate_timestamp(0, TEST_BLOCK_TIMESTAMP);
- config.validate_timestamp(1, TEST_BLOCK_TIMESTAMP + 60000);
- config.validate_timestamp(2, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS);
- config.validate_timestamp(3, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS);
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP - 60000);
- }
-
- #[should_panic(expected = "Timestamp 2000000180001 is too future for #0")]
- #[test]
- fn test_validate_timestamp_too_future() {
- Config::test().validate_timestamp(0, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS + 1);
- }
-
- #[should_panic(expected = "Timestamp 1999999099999 is too old for #1")]
- #[test]
- fn test_validate_timestamp_too_old() {
- Config::test().validate_timestamp(1, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS - 1);
- }
-
- #[should_panic(expected = "Timestamp 0 is too old for #2")]
- #[test]
- fn test_validate_timestamp_zero() {
- Config::test().validate_timestamp(2, 0);
- }
-
- #[should_panic(expected = "Timestamp 4000000000000 is too future for #3")]
- #[test]
- fn test_validate_timestamp_big() {
- Config::test().validate_timestamp(3, TEST_BLOCK_TIMESTAMP + TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Timestamp 2000000000000 is too future for #4")]
- #[test]
- fn test_validate_timestamp_no_block_timestamp() {
- let mut config = Config::test();
-
- config.block_timestamp = 0;
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #0 (ETH)")]
- #[test]
- fn test_validate_signer_count_threshold_empty_list() {
- Config::test().validate_signer_count_threshold(0, vec![].as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_shorter_list() {
- Config::test().validate_signer_count_threshold(1, vec![1u8].iter_into_opt().as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_list_with_nones() {
- Config::test().validate_signer_count_threshold(
- 1,
- vec![None, 1u8.into(), None].opt_iter_into_opt().as_slice(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_size() {
- validate_with_all_permutations(vec![1u8, 2].iter_into_opt(), vec![1u8, 2].iter_into());
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_signer_count() {
- validate_with_all_permutations(
- vec![None, 1u8.into(), None, 2.into()].opt_iter_into_opt(),
- vec![1u8, 2].iter_into(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_larger_size() {
- validate_with_all_permutations(
- vec![
- 1u8.into(),
- None,
- None,
- 2.into(),
- 3.into(),
- None,
- 4.into(),
- None,
- ]
- .opt_iter_into_opt(),
- vec![1u8, 2, 3, 4].iter_into(),
- );
- }
-
- fn validate_with_all_permutations(numbers: Vec<Option<U256>>, expected_value: Vec<U256>) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
- let mut config = Config::test();
-
- let result = config.validate_signer_count_threshold(0, &numbers);
- assert_eq!(result, expected_value);
-
- for threshold in 0..expected_value.len() + 1 {
- config.signer_count_threshold = threshold as u8;
-
- for (index, perm) in perms.iter().enumerate() {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- let result =
- config.validate_signer_count_threshold(index % config.feed_ids.len(), &p);
- assert_eq!(result.len(), expected_value.len());
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -
use sha3::{Digest, Keccak256};
-
-pub fn keccak256(data: &[u8]) -> Box<[u8]> {
- Keccak256::new_with_prefix(data)
- .finalize()
- .as_slice()
- .into()
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{crypto::keccak256::keccak256, helpers::hex::hex_to_bytes};
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const EMPTY_MESSAGE_HASH: &str =
- "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
-
- #[test]
- fn test_keccak256() {
- let hash = keccak256(hex_to_bytes(MESSAGE.into()).as_slice());
-
- assert_eq!(hash.as_ref(), hex_to_bytes(MESSAGE_HASH.into()).as_slice());
- }
-
- #[test]
- fn test_keccak256_empty() {
- let hash = keccak256(vec![].as_slice());
-
- assert_eq!(
- hash.as_ref(),
- hex_to_bytes(EMPTY_MESSAGE_HASH.into()).as_slice()
- );
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -
use crate::crypto::{keccak256, recover::crypto256::recover_public_key};
-
-pub fn recover_address(message: Vec<u8>, signature: Vec<u8>) -> Vec<u8> {
- let recovery_byte = signature[64]; // 65-byte representation
- let msg_hash = keccak256::keccak256(message.as_slice());
- let key = recover_public_key(
- msg_hash,
- &signature[..64],
- recovery_byte - (if recovery_byte >= 27 { 27 } else { 0 }),
- );
- let key_hash = keccak256::keccak256(&key[1..]); // skip first uncompressed-key byte
-
- key_hash[12..].into() // last 20 bytes
-}
-
-#[cfg(feature = "crypto_secp256k1")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use secp256k1::{ecdsa::RecoverableSignature, Message, Secp256k1 as Secp256k1Curve};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let msg = Message::from_digest_slice(message_hash.as_ref())
- .unwrap_or_revert(|_| Error::CryptographicError(message_hash.len()));
-
- let recovery_id = secp256k1::ecdsa::RecoveryId::from_i32(recovery_byte.into())
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let sig: RecoverableSignature =
- RecoverableSignature::from_compact(signature_bytes, recovery_id)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let public_key = Secp256k1Curve::new().recover_ecdsa(&msg, &sig);
-
- public_key.unwrap().serialize_uncompressed().into()
- }
-}
-
-#[cfg(feature = "crypto_k256")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let recovery_id = RecoveryId::from_byte(recovery_byte)
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let signature = Signature::try_from(signature_bytes)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let recovered_key =
- VerifyingKey::recover_from_prehash(message_hash.as_ref(), &signature, recovery_id)
- .map(|key| key.to_encoded_point(false).to_bytes());
-
- recovered_key.unwrap()
- }
-}
-
-#[cfg(all(not(feature = "crypto_k256"), not(feature = "crypto_secp256k1")))]
-pub(crate) mod crypto256 {
- pub(crate) fn recover_public_key(
- _message_hash: Box<[u8]>,
- _signature_bytes: &[u8],
- _recovery_byte: u8,
- ) -> Box<[u8]> {
- panic!("Not implemented!")
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- crypto::recover::{crypto256::recover_public_key, recover_address},
- helpers::hex::hex_to_bytes,
- };
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const SIG_V27: &str = "475195641dae43318e194c3d9e5fc308773d6fdf5e197e02644dfd9ca3d19e3e2bd7d8656428f7f02e658a16b8f83722169c57126cc50bec8fad188b1bac6d19";
- const SIG_V28: &str = "c88242d22d88252c845b946c9957dbf3c7d59a3b69ecba2898198869f9f146ff268c3e47a11dbb05cc5198aadd659881817a59ee37e088d3253f4695927428c1";
- const PUBLIC_KEY_V27: &str =
- "04f5f035588502146774d0ccfd62ee5bf1d7f1dbb96aae33a79765c636b8ec75a36f5121931b5cc37215a7d4280c5700ca92daaaf93c32b06ca9f98b1f4ece624e";
- const PUBLIC_KEY_V28: &str =
- "04626f2ad2cfb0b41a24276d78de8959bcf45fc5e80804416e660aab2089d15e98206526e639ee19d17c8f9ae0ce3a6ff1a8ea4ab773d0fb4214e08aad7ba978c8";
- const ADDRESS_V27: &str = "2c59617248994D12816EE1Fa77CE0a64eEB456BF";
- const ADDRESS_V28: &str = "12470f7aBA85c8b81D63137DD5925D6EE114952b";
-
- #[test]
- fn test_recover_public_key_v27() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V27), 0);
-
- assert_eq!(u8_box(PUBLIC_KEY_V27), public_key);
- }
-
- #[test]
- fn test_recover_public_key_v28() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V28), 1);
-
- assert_eq!(u8_box(PUBLIC_KEY_V28), public_key);
- }
-
- #[test]
- fn test_recover_address_1b() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V27.to_owned() + "1b"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V27.into()), address);
- }
-
- #[test]
- fn test_recover_address_1c() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V28.to_owned() + "1c"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V28.into()), address);
- }
-
- fn u8_box(str: &str) -> Box<[u8]> {
- hex_to_bytes(str.into()).as_slice().into()
- }
-}
-
//! # RedStone
-//!
-//! `redstone` is a collection of utilities to make deserializing&decrypting RedStone payload.
-//! It includes a pure Rust implementation, along with extensions for certain networks.
-//!
-//! Different crypto-mechanisms are easily injectable.
-//! The current implementation contains `secp256k1`- and `k256`-based variants.
-
-pub mod core;
-mod crypto;
-pub mod network;
-mod protocol;
-mod utils;
-
-#[cfg(feature = "helpers")]
-pub mod helpers;
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -
extern crate alloc;
-
-use crate::network::specific::U256;
-use alloc::{format, string::String};
-
-pub trait AsHexStr {
- fn as_hex_str(&self) -> String;
-}
-
-impl AsHexStr for &[u8] {
- #[allow(clippy::format_collect)]
- fn as_hex_str(&self) -> String {
- self.iter().map(|byte| format!("{:02x}", byte)).collect()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsHexStr for casper_types::bytesrepr::Bytes {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- format!("{:X}", self)
- }
-}
-
-#[cfg(feature = "network_radix")]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- let digits = self.to_digits();
- let mut result = String::new();
- for &part in &digits {
- if result.is_empty() || part != 0u64 {
- result.push_str(&format!("{:02X}", part));
- }
- }
- result
- }
-}
-
-impl AsHexStr for Vec<u8> {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-impl AsHexStr for Box<[u8]> {
- fn as_hex_str(&self) -> String {
- self.as_ref().as_hex_str()
- }
-}
-
-pub trait AsAsciiStr {
- fn as_ascii_str(&self) -> String;
-}
-
-impl AsAsciiStr for &[u8] {
- fn as_ascii_str(&self) -> String {
- self.iter().map(|&code| code as char).collect()
- }
-}
-
-impl AsAsciiStr for Vec<u8> {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsAsciiStr for casper_types::bytesrepr::Bytes {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-impl AsAsciiStr for U256 {
- fn as_ascii_str(&self) -> String {
- let hex_string = self.as_hex_str();
- let bytes = (0..hex_string.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&hex_string[i..i + 2], 16))
- .collect::<Result<Vec<u8>, _>>()
- .unwrap();
-
- bytes.as_ascii_str()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
- };
-
- const ETH: u32 = 4543560u32;
-
- #[test]
- fn test_as_hex_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_hex_str();
-
- assert_eq!(result, "455448");
- }
-
- #[test]
- fn test_as_ascii_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_ascii_str();
-
- assert_eq!(result, "ETH");
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -
use crate::{
- network::{error::Error, specific::revert},
- print_debug,
-};
-use std::fmt::Debug;
-
-pub trait Assert<F> {
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
-
-impl<T, F> Assert<F> for T
-where
- T: Debug,
- F: Fn(&Self) -> bool,
-{
- fn assert_or_revert<E: FnOnce(&Self) -> Error>(self, check: F, error: E) -> Self {
- assert_or_revert(self, check, error)
- }
-}
-
-#[inline]
-fn assert_or_revert<F, T, E: FnOnce(&T) -> Error>(arg: T, check: F, error: E) -> T
-where
- F: Fn(&T) -> bool,
- T: Debug,
-{
- assert_or_revert_bool_with(check(&arg), || error(&arg));
-
- arg
-}
-
-#[inline]
-fn assert_or_revert_bool_with<E: FnOnce() -> Error>(check: bool, error: E) {
- if check {
- return;
- }
-
- let error = error();
- print_debug!("REVERT({}) - {}!", &error.code(), error);
- revert(error);
-}
-
-pub trait Unwrap<R> {
- type ErrorArg;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
-
-impl<T> Unwrap<T> for Option<T>
-where
- T: Debug,
-{
- type ErrorArg = ();
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(self, |arg| arg.is_some(), |_| error(&())).unwrap()
- }
-}
-
-impl<T, Err> Unwrap<T> for Result<T, Err>
-where
- T: Debug,
- Err: Debug,
-{
- type ErrorArg = Err;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(
- self,
- |arg| arg.is_ok(),
- |e| error(e.as_ref().err().unwrap()),
- )
- .unwrap()
- }
-}
-
-#[cfg(test)]
-mod assert_or_revert_tests {
- use crate::network::{
- assert::{assert_or_revert_bool_with, Assert},
- error::Error,
- };
-
- #[test]
- fn test_assert_or_revert_bool_with_true() {
- assert_or_revert_bool_with(true, || Error::ArrayIsEmpty);
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_assert_or_revert_bool_with_false() {
- assert_or_revert_bool_with(false, || Error::ArrayIsEmpty);
- }
-
- #[test]
- fn test_assert_or_revert_correct() {
- 5.assert_or_revert(|&x| x == 5, |&size| Error::SizeNotSupported(size));
- }
-
- #[should_panic(expected = "Size not supported: 5")]
- #[test]
- fn test_assert_or_revert_wrong() {
- 5.assert_or_revert(|&x| x < 5, |&size| Error::SizeNotSupported(size));
- }
-}
-
-#[cfg(test)]
-mod unwrap_or_revert_tests {
- use crate::network::{assert::Unwrap, error::Error};
-
- #[test]
- fn test_unwrap_or_revert_some() {
- let result = Some(543).unwrap_or_revert(|_| Error::CryptographicError(333));
-
- assert_eq!(result, 543);
- }
-
- #[should_panic(expected = "Cryptographic Error: 333")]
- #[test]
- fn test_unwrap_or_revert_none() {
- (Option::<u64>::None).unwrap_or_revert(|_| Error::CryptographicError(333));
- }
-
- #[test]
- fn test_unwrap_or_revert_ok() {
- let result = Ok(256).unwrap_or_revert(|_: &Error| Error::CryptographicError(333));
-
- assert_eq!(result, 256);
- }
-
- #[should_panic(expected = "Cryptographic Error: 567")]
- #[test]
- fn test_unwrap_or_revert_err() {
- Result::<&[u8], Error>::Err(Error::CryptographicError(567)).unwrap_or_revert(|e| e.clone());
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod error;
-mod from_bytes_repr;
-
-pub struct Casper;
-
-impl NetworkSpecific for Casper {
- type BytesRepr = casper_types::bytesrepr::Bytes;
- type ValueRepr = casper_types::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- casper_contract::contract_api::runtime::print(&_text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- casper_contract::contract_api::runtime::revert(error)
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -
use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
-};
-use std::fmt::{Debug, Display, Formatter};
-
-pub trait ContractErrorContent: Debug {
- fn code(&self) -> u8;
- fn message(&self) -> String;
-}
-
-/// Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-///
-/// These errors include issues with contract logic, data types,
-/// cryptographic operations, and conditions specific to the requirements.
-#[derive(Debug)]
-pub enum Error {
- /// Represents errors that arise from the contract itself.
- ///
- /// This variant is used for encapsulating errors that are specific to the contract's logic
- /// or execution conditions that aren't covered by more specific error types.
- ContractError(Box<dyn ContractErrorContent>),
-
- /// Indicates an overflow error with `U256` numbers.
- ///
- /// Used when operations on `U256` numbers exceed their maximum value, potentially leading
- /// to incorrect calculations or state.
- NumberOverflow(U256),
-
- /// Used when an expected non-empty array or vector is found to be empty.
- ///
- /// This could occur in scenarios where the contract logic requires a non-empty collection
- /// of items for the correct operation, for example, during aggregating the values.
- ArrayIsEmpty,
-
- /// Represents errors related to cryptographic operations.
- ///
- /// This includes failures in signature verification, hashing, or other cryptographic
- /// processes, with the usize indicating the position or identifier of the failed operation.
- CryptographicError(usize),
-
- /// Signifies that an unsupported size was encountered.
- ///
- /// This could be used when a data structure or input does not meet the expected size
- /// requirements for processing.
- SizeNotSupported(usize),
-
- /// Indicates that the marker bytes for RedStone are incorrect.
- ///
- /// This error is specific to scenarios where marker or identifier bytes do not match
- /// expected values, potentially indicating corrupted or tampered data.
- WrongRedStoneMarker(Vec<u8>),
-
- /// Used when there is leftover data in a payload that should have been empty.
- ///
- /// This could indicate an error in data parsing or that additional, unexpected data
- /// was included in a message or transaction.
- NonEmptyPayloadRemainder(Vec<u8>),
-
- /// Indicates that the number of signers does not meet the required threshold.
- ///
- /// This variant includes the current number of signers, the required threshold, and
- /// potentially a feed_id related to the operation that failed due to insufficient signers.
- InsufficientSignerCount(usize, usize, U256),
-
- /// Used when a timestamp is older than allowed by the processor logic.
- ///
- /// Includes the position or identifier of the timestamp and the threshold value,
- /// indicating that the provided timestamp is too far in the past.
- TimestampTooOld(usize, u64),
-
- /// Indicates that a timestamp is further in the future than allowed.
- ///
- /// Similar to `TimestampTooOld`, but for future timestamps exceeding the contract's
- /// acceptance window.
- TimestampTooFuture(usize, u64),
-
- /// Represents errors that need to clone `ContractErrorContent`, which is not supported by default.
- ///
- /// This variant allows for the manual duplication of contract error information, including
- /// an error code and a descriptive message.
- ClonedContractError(u8, String),
-}
-
-impl Error {
- pub fn contract_error<T: ContractErrorContent + 'static>(value: T) -> Error {
- Error::ContractError(Box::new(value))
- }
-
- pub(crate) fn code(&self) -> u16 {
- match self {
- Error::ContractError(boxed) => boxed.code() as u16,
- Error::NumberOverflow(_) => 509,
- Error::ArrayIsEmpty => 510,
- Error::WrongRedStoneMarker(_) => 511,
- Error::NonEmptyPayloadRemainder(_) => 512,
- Error::InsufficientSignerCount(data_package_index, value, _) => {
- (2000 + data_package_index * 10 + value) as u16
- }
- Error::SizeNotSupported(size) => 600 + *size as u16,
- Error::CryptographicError(size) => 700 + *size as u16,
- Error::TimestampTooOld(data_package_index, _) => 1000 + *data_package_index as u16,
- Error::TimestampTooFuture(data_package_index, _) => 1050 + *data_package_index as u16,
- Error::ClonedContractError(code, _) => *code as u16,
- }
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- Error::ContractError(boxed) => write!(f, "Contract error: {}", boxed.message()),
- Error::NumberOverflow(number) => write!(f, "Number overflow: {}", number),
- Error::ArrayIsEmpty => write!(f, "Array is empty"),
- Error::CryptographicError(size) => write!(f, "Cryptographic Error: {}", size),
- Error::SizeNotSupported(size) => write!(f, "Size not supported: {}", size),
- Error::WrongRedStoneMarker(bytes) => {
- write!(f, "Wrong RedStone marker: {}", bytes.as_hex_str())
- }
- Error::NonEmptyPayloadRemainder(bytes) => {
- write!(f, "Non empty payload remainder: {}", bytes.as_hex_str())
- }
- Error::InsufficientSignerCount(data_package_index, value, feed_id) => write!(
- f,
- "Insufficient signer count {} for #{} ({})",
- value,
- data_package_index,
- feed_id.as_ascii_str()
- ),
- Error::TimestampTooOld(data_package_index, value) => {
- write!(
- f,
- "Timestamp {} is too old for #{}",
- value, data_package_index
- )
- }
- Error::TimestampTooFuture(data_package_index, value) => write!(
- f,
- "Timestamp {} is too future for #{}",
- value, data_package_index
- ),
- Error::ClonedContractError(_, message) => {
- write!(f, "(Cloned) Contract error: {}", message)
- }
- }
- }
-}
-
-impl Clone for Error {
- fn clone(&self) -> Self {
- match self {
- Error::ContractError(content) => {
- Error::ClonedContractError(content.code(), content.message())
- }
- Error::NumberOverflow(value) => Error::NumberOverflow(*value),
- Error::ArrayIsEmpty => Error::ArrayIsEmpty,
- Error::CryptographicError(size) => Error::CryptographicError(*size),
- Error::SizeNotSupported(size) => Error::SizeNotSupported(*size),
- Error::WrongRedStoneMarker(bytes) => Error::WrongRedStoneMarker(bytes.clone()),
- Error::NonEmptyPayloadRemainder(bytes) => {
- Error::NonEmptyPayloadRemainder(bytes.clone())
- }
- Error::InsufficientSignerCount(count, needed, bytes) => {
- Error::InsufficientSignerCount(*count, *needed, *bytes)
- }
- Error::TimestampTooOld(index, timestamp) => Error::TimestampTooOld(*index, *timestamp),
- Error::TimestampTooFuture(index, timestamp) => {
- Error::TimestampTooFuture(*index, *timestamp)
- }
- Error::ClonedContractError(code, message) => {
- Error::ClonedContractError(*code, message.as_str().into())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -
use crate::network::specific::Bytes;
-
-pub trait Flattened<T> {
- fn flattened(&self) -> T;
-}
-
-impl Flattened<Bytes> for Vec<Bytes> {
- fn flattened(&self) -> Bytes {
- #[allow(clippy::useless_conversion)]
- self.iter().flatten().copied().collect::<Vec<_>>().into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{flattened::Flattened, specific::Bytes};
-
- #[test]
- fn test_bytes_flattened() {
- #[allow(clippy::useless_conversion)]
- let bytes: Vec<Bytes> = vec![
- vec![1u8, 2, 3].into(),
- vec![4u8].into(),
- vec![].into(),
- vec![5, 6, 7].into(),
- ];
-
- let result: Bytes = bytes.flattened();
-
- #[allow(clippy::useless_conversion)]
- let expected_result: Bytes = vec![1u8, 2, 3, 4, 5, 6, 7].into();
-
- assert_eq!(result, expected_result);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -
use crate::network::specific::VALUE_SIZE;
-
-pub trait FromBytesRepr<T> {
- fn from_bytes_repr(bytes: T) -> Self;
-}
-
-pub trait Sanitized {
- fn sanitized(self) -> Self;
-}
-
-impl Sanitized for Vec<u8> {
- fn sanitized(self) -> Self {
- if self.len() <= VALUE_SIZE {
- return self;
- }
-
- let index = self.len().max(VALUE_SIZE) - VALUE_SIZE;
- let remainder = &self[0..index];
-
- if remainder != vec![0; index] {
- panic!("Number to big: {:?} digits", self.len())
- }
-
- self[index..].into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- };
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[test]
- fn test_from_bytes_repr_single() {
- let vec = vec![1];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(1u32));
- }
-
- #[test]
- fn test_from_bytes_repr_double() {
- let vec = vec![1, 2];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(258u32));
- }
-
- #[test]
- fn test_from_bytes_repr_simple() {
- let vec = vec![1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[test]
- fn test_from_bytes_repr_bigger() {
- let vec = vec![101, 202, 255];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(6671103u32));
- }
-
- #[test]
- fn test_from_bytes_repr_empty() {
- let result = U256::from_bytes_repr(Vec::new());
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[test]
- fn test_from_bytes_repr_trailing_zeroes() {
- let vec = vec![1, 2, 3, 0];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(16909056u32));
- }
-
- #[test]
- fn test_from_bytes_repr_leading_zeroes() {
- let vec = vec![0, 1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_max() {
- let vec = vec![255; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-
- #[test]
- fn test_from_bytes_repr_min() {
- let vec = vec![0; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[should_panic(expected = "Number to big")]
- #[test]
- fn test_from_bytes_repr_too_long() {
- let x = VALUE_SIZE as u8 + 1;
- let vec = (1..=x).collect();
-
- U256::from_bytes_repr(vec);
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_too_long_but_zeroes() {
- let mut vec = vec![255; VALUE_SIZE + 1];
- vec[0] = 0;
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-}
-
pub mod as_str;
-pub mod assert;
-pub mod error;
-pub mod from_bytes_repr;
-pub mod print_debug;
-pub mod specific;
-
-#[cfg(feature = "network_casper")]
-pub mod casper;
-
-#[cfg(feature = "network_casper")]
-pub type _Network = casper::Casper;
-
-#[cfg(feature = "network_radix")]
-pub mod radix;
-
-#[cfg(feature = "network_radix")]
-pub type _Network = radix::Radix;
-
-pub mod flattened;
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-mod pure;
-
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-pub type _Network = pure::Std;
-
extern crate alloc;
-
-#[macro_export]
-macro_rules! print_debug {
- ($fmt:expr) => {
- $crate::network::specific::print(format!($fmt))
- };
- ($fmt:expr, $($args:tt)*) => {
- $crate::network::specific::print(format!($fmt, $($args)*))
- };
-}
-
-#[macro_export]
-macro_rules! print_and_panic {
- ($fmt:expr) => {{
- $crate::print_debug!($fmt);
- panic!($fmt)
- }};
- ($fmt:expr, $($args:tt)*) => {{
- $crate::print_debug!($fmt, $($args)*);
- panic!($fmt, $($args)*)
- }};
-}
-
use crate::network::{error::Error, specific::NetworkSpecific};
-use primitive_types::U256;
-use std::eprintln;
-
-mod from_bytes_repr;
-
-pub struct Std;
-
-impl NetworkSpecific for Std {
- type BytesRepr = Vec<u8>;
- type ValueRepr = U256;
- type _Self = Std;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(text: String) {
- eprintln!("{}", text)
- }
-
- fn revert(error: Error) -> ! {
- panic!("{}", error)
- }
-}
-
use crate::network::{_Network, error::Error, from_bytes_repr::FromBytesRepr};
-
-pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
-
-pub(crate) type Network = <_Network as NetworkSpecific>::_Self;
-pub type Bytes = <_Network as NetworkSpecific>::BytesRepr;
-pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
-pub const VALUE_SIZE: usize = <_Network as NetworkSpecific>::VALUE_SIZE;
-
-pub fn print(_text: String) {
- Network::print(_text)
-}
-
-pub fn revert(error: Error) -> ! {
- Network::revert(error)
-}
-
pub(crate) const UNSIGNED_METADATA_BYTE_SIZE_BS: usize = 3;
-pub(crate) const DATA_PACKAGES_COUNT_BS: usize = 2;
-pub(crate) const DATA_POINTS_COUNT_BS: usize = 3;
-pub(crate) const SIGNATURE_BS: usize = 65;
-pub(crate) const DATA_POINT_VALUE_BYTE_SIZE_BS: usize = 4;
-pub(crate) const DATA_FEED_ID_BS: usize = 32;
-pub(crate) const TIMESTAMP_BS: usize = 6;
-pub(crate) const MAX_TIMESTAMP_DELAY_MS: u64 = 15 * 60 * 1000; // 15 minutes in milliseconds
-pub(crate) const MAX_TIMESTAMP_AHEAD_MS: u64 = 3 * 60 * 1000; // 3 minutes in milliseconds
-pub(crate) const REDSTONE_MARKER_BS: usize = 9;
-pub(crate) const REDSTONE_MARKER: [u8; 9] = [0, 0, 2, 237, 87, 1, 30, 0, 0]; // 0x000002ed57011e0000
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -
use crate::{
- crypto::recover::recover_address,
- network::as_str::AsHexStr,
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_point::{trim_data_points, DataPoint},
- },
- utils::trim::Trim,
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
-
-pub(crate) fn trim_data_packages(payload: &mut Vec<u8>, count: usize) -> Vec<DataPackage> {
- let mut data_packages = Vec::new();
-
- for _ in 0..count {
- let data_package = trim_data_package(payload);
- data_packages.push(data_package);
- }
-
- data_packages
-}
-
-fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage {
- let signature = payload.trim_end(SIGNATURE_BS);
- let mut tmp = payload.clone();
-
- let data_point_count = payload.trim_end(DATA_POINTS_COUNT_BS);
- let value_size = payload.trim_end(DATA_POINT_VALUE_BYTE_SIZE_BS);
- let timestamp = payload.trim_end(TIMESTAMP_BS);
- let size = data_point_count * (value_size + DATA_FEED_ID_BS)
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + DATA_POINTS_COUNT_BS;
-
- let signable_bytes = tmp.trim_end(size);
- let signer_address = recover_address(signable_bytes, signature);
-
- let data_points = trim_data_points(payload, data_point_count, value_size);
-
- DataPackage {
- data_points,
- timestamp,
- signer_address,
- }
-}
-
-impl Debug for DataPackage {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPackage {{\n signer_address: 0x{}, timestamp: {},\n data_points: {:?}\n}}",
- self.signer_address.as_hex_str(),
- self.timestamp,
- self.data_points
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{from_bytes_repr::FromBytesRepr, specific::U256},
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_package::{trim_data_package, trim_data_packages, DataPackage},
- data_point::DataPoint,
- },
- };
-
- const DATA_PACKAGE_BYTES_1: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e018d79bf0ba00000002000000151afa8c5c3caf6004b42c0fb17723e524f993b9ecbad3b9bce5ec74930fa436a3660e8edef10e96ee5f222de7ef5787c02ca467c0ec18daa2907b43ac20c63c11c";
- const DATA_PACKAGE_BYTES_2: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cdd851e018d79bf0ba000000020000001473fd9dc72e6814a7de719b403cf4c9eba08934a643fd0666c433b806b31e69904f2226ffd3c8ef75861b11b5e32a1fda4b1458e0da4605a772dfba2a812f3ee1b";
-
- const SIGNER_ADDRESS_1: &str = "1ea62d73edf8ac05dfcea1a34b9796e937a29eff";
- const SIGNER_ADDRESS_2: &str = "109b4a318a4f5ddcbca6349b45f881b4137deafb";
-
- const VALUE_1: u128 = 232141080910;
- const VALUE_2: u128 = 232144078110;
-
- const DATA_PACKAGE_SIZE: usize = 32
- + DATA_FEED_ID_BS
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + SIGNATURE_BS
- + DATA_POINTS_COUNT_BS;
-
- #[test]
- fn test_trim_data_packages() {
- test_trim_data_packages_of(2, "");
- test_trim_data_packages_of(0, "");
- test_trim_data_packages_of(1, "");
- }
-
- #[test]
- fn test_trim_data_packages_with_prefix() {
- let prefix = "da4687f1914a1c";
-
- test_trim_data_packages_of(2, prefix);
- }
-
- #[test]
- fn test_trim_data_packages_single() {
- let mut bytes = hex_to_bytes(DATA_PACKAGE_BYTES_1.into());
- let data_packages = trim_data_packages(&mut bytes, 1);
- assert_eq!(data_packages.len(), 1);
- assert_eq!(bytes, Vec::<u8>::new());
-
- verify_data_package(data_packages[0].clone(), VALUE_1, SIGNER_ADDRESS_1);
- }
-
- fn test_trim_data_packages_of(count: usize, prefix: &str) {
- let input: Vec<u8> =
- hex_to_bytes((prefix.to_owned() + DATA_PACKAGE_BYTES_1) + DATA_PACKAGE_BYTES_2);
- let mut bytes = input.clone();
- let data_packages = trim_data_packages(&mut bytes, count);
-
- assert_eq!(data_packages.len(), count);
- assert_eq!(
- bytes.as_slice(),
- &input[..input.len() - count * DATA_PACKAGE_SIZE]
- );
-
- let values = &[VALUE_2, VALUE_1];
- let signers = &[SIGNER_ADDRESS_2, SIGNER_ADDRESS_1];
-
- for i in 0..count {
- verify_data_package(data_packages[i].clone(), values[i], signers[i]);
- }
- }
-
- #[should_panic(expected = "index out of bounds")]
- #[test]
- fn test_trim_data_packages_bigger_number() {
- test_trim_data_packages_of(3, "");
- }
-
- #[test]
- fn test_trim_data_package() {
- test_trim_data_package_of(DATA_PACKAGE_BYTES_1, VALUE_1, SIGNER_ADDRESS_1);
- test_trim_data_package_of(DATA_PACKAGE_BYTES_2, VALUE_2, SIGNER_ADDRESS_2);
- }
-
- #[test]
- fn test_trim_data_package_with_prefix() {
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_1),
- VALUE_1,
- SIGNER_ADDRESS_1,
- );
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_2),
- VALUE_2,
- SIGNER_ADDRESS_2,
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_signature_only() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1[(DATA_PACKAGE_BYTES_1.len() - 2 * SIGNATURE_BS)..],
- 0,
- "",
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_shorter() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1
- [(DATA_PACKAGE_BYTES_1.len() - 2 * (SIGNATURE_BS + DATA_POINTS_COUNT_BS))..],
- 0,
- "",
- );
- }
-
- fn test_trim_data_package_of(bytes_str: &str, expected_value: u128, signer_address: &str) {
- let mut bytes: Vec<u8> = hex_to_bytes(bytes_str.into());
- let result = trim_data_package(&mut bytes);
- assert_eq!(
- bytes,
- hex_to_bytes(bytes_str[..bytes_str.len() - 2 * (DATA_PACKAGE_SIZE)].into())
- );
-
- verify_data_package(result, expected_value, signer_address);
- }
-
- fn verify_data_package(result: DataPackage, expected_value: u128, signer_address: &str) {
- let data_package = DataPackage {
- data_points: vec![DataPoint {
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_PACKAGE_BYTES_1[..6].into())),
- value: U256::from(expected_value),
- }],
- timestamp: 1707144580000,
- signer_address: hex_to_bytes(signer_address.into()),
- };
-
- assert_eq!(result, data_package);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -
use crate::{
- network::{
- as_str::{AsAsciiStr, AsHexStr},
- assert::Assert,
- error::Error,
- from_bytes_repr::FromBytesRepr,
- specific::U256,
- },
- protocol::constants::DATA_FEED_ID_BS,
- utils::{trim::Trim, trim_zeros::TrimZeros},
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
-
-pub(crate) fn trim_data_points(
- payload: &mut Vec<u8>,
- count: usize,
- value_size: usize,
-) -> Vec<DataPoint> {
- count.assert_or_revert(|&count| count == 1, |&count| Error::SizeNotSupported(count));
-
- let mut data_points = Vec::new();
-
- for _ in 0..count {
- let data_point = trim_data_point(payload, value_size);
- data_points.push(data_point);
- }
-
- data_points
-}
-
-fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint {
- let value = payload.trim_end(value_size);
- let feed_id: Vec<u8> = payload.trim_end(DATA_FEED_ID_BS);
-
- DataPoint {
- value,
- feed_id: U256::from_bytes_repr(feed_id.trim_zeros()),
- }
-}
-
-impl Debug for DataPoint {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPoint {{\n feed_id: {:?} (0x{}), value: {}\n }}",
- self.feed_id.as_ascii_str(),
- self.feed_id.as_hex_str(),
- self.value,
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- },
- protocol::{
- constants::DATA_FEED_ID_BS,
- data_point::{trim_data_point, trim_data_points, DataPoint},
- },
- };
- use std::ops::Shr;
-
- const DATA_POINT_BYTES_TAIL: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e";
- const VALUE: u128 = 232141080910;
-
- #[test]
- fn test_trim_data_points() {
- let mut bytes = hex_to_bytes(DATA_POINT_BYTES_TAIL.into());
- let result = trim_data_points(&mut bytes, 1, 32);
-
- assert_eq!(result.len(), 1);
-
- verify_rest_and_result(
- DATA_POINT_BYTES_TAIL,
- 32,
- VALUE.into(),
- bytes,
- result[0].clone(),
- )
- }
-
- #[should_panic(expected = "Size not supported: 0")]
- #[test]
- fn test_trim_zero_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 0, 32);
- }
-
- #[should_panic(expected = "Size not supported: 2")]
- #[test]
- fn test_trim_two_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 2, 32);
- }
-
- #[test]
- fn test_trim_data_point() {
- test_trim_data_point_of(DATA_POINT_BYTES_TAIL, 32, VALUE.into());
- }
-
- #[test]
- fn test_trim_data_point_with_prefix() {
- test_trim_data_point_of(
- &("a2a812f3ee1b".to_owned() + DATA_POINT_BYTES_TAIL),
- 32,
- VALUE.into(),
- );
- }
-
- #[test]
- fn test_trim_data_point_other_lengths() {
- for i in 1..VALUE_SIZE {
- test_trim_data_point_of(
- &DATA_POINT_BYTES_TAIL[..DATA_POINT_BYTES_TAIL.len() - 2 * i],
- 32 - i,
- U256::from(VALUE).shr(8 * i as u32),
- );
- }
- }
-
- fn test_trim_data_point_of(value: &str, size: usize, expected_value: U256) {
- let mut bytes = hex_to_bytes(value.into());
- let result = trim_data_point(&mut bytes, size);
-
- verify_rest_and_result(value, size, expected_value, bytes, result);
- }
-
- fn verify_rest_and_result(
- value: &str,
- size: usize,
- expected_value: U256,
- rest: Vec<u8>,
- result: DataPoint,
- ) {
- assert_eq!(
- rest,
- hex_to_bytes(value[..value.len() - 2 * (size + DATA_FEED_ID_BS)].into())
- );
-
- let data_point = DataPoint {
- value: expected_value,
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_POINT_BYTES_TAIL[..6].to_string())),
- };
-
- assert_eq!(result, data_point);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
-};
-
-pub fn trim_redstone_marker(payload: &mut Vec<u8>) {
- let marker: Vec<u8> = payload.trim_end(REDSTONE_MARKER_BS);
-
- marker.as_slice().assert_or_revert(
- |&marker| marker == REDSTONE_MARKER,
- |&val| Error::WrongRedStoneMarker(val.into()),
- );
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- protocol::{constants::REDSTONE_MARKER_BS, marker::trim_redstone_marker},
- };
-
- const PAYLOAD_TAIL: &str = "1c000f000000000002ed57011e0000";
-
- #[test]
- fn test_trim_redstone_marker() {
- let mut bytes = hex_to_bytes(PAYLOAD_TAIL.into());
- trim_redstone_marker(&mut bytes);
-
- assert_eq!(
- bytes,
- hex_to_bytes(PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2 * REDSTONE_MARKER_BS].into())
- );
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 000002ed57022e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong() {
- trim_redstone_marker(&mut hex_to_bytes(PAYLOAD_TAIL.replace('1', "2")));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 00000002ed57011e00")]
- #[test]
- fn test_trim_redstone_marker_wrong_ending() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2].into(),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 100002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong_beginning() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL.replace("0000000", "1111111"),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 0002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_too_short() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[PAYLOAD_TAIL.len() - 2 * (REDSTONE_MARKER_BS - 1)..].into(),
- ));
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::{
- constants::{DATA_PACKAGES_COUNT_BS, UNSIGNED_METADATA_BYTE_SIZE_BS},
- data_package::{trim_data_packages, DataPackage},
- marker,
- },
- utils::trim::Trim,
-};
-
-#[derive(Clone, Debug)]
-pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
-
-impl Payload {
- pub(crate) fn make(payload_bytes: &mut Vec<u8>) -> Payload {
- marker::trim_redstone_marker(payload_bytes);
- let payload = trim_payload(payload_bytes);
-
- payload_bytes.assert_or_revert(
- |bytes| bytes.is_empty(),
- |bytes| Error::NonEmptyPayloadRemainder(bytes.as_slice().into()),
- );
-
- payload
- }
-}
-
-fn trim_payload(payload: &mut Vec<u8>) -> Payload {
- let data_package_count = trim_metadata(payload);
- let data_packages = trim_data_packages(payload, data_package_count);
-
- Payload { data_packages }
-}
-
-fn trim_metadata(payload: &mut Vec<u8>) -> usize {
- let unsigned_metadata_size = payload.trim_end(UNSIGNED_METADATA_BYTE_SIZE_BS);
- let _: Vec<u8> = payload.trim_end(unsigned_metadata_size);
-
- payload.trim_end(DATA_PACKAGES_COUNT_BS)
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::{hex_to_bytes, read_payload_bytes, read_payload_hex},
- protocol::{
- constants::REDSTONE_MARKER_BS,
- payload::{trim_metadata, trim_payload, Payload},
- },
- };
-
- const PAYLOAD_METADATA_BYTES: &str = "000f000000";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTE: &str = "000f55000001";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTES: &str = "000f11223344556677889900aabbccddeeff000010";
-
- #[test]
- fn test_trim_metadata() {
- let prefix = "9e0294371c";
-
- for &bytes_str in &[
- PAYLOAD_METADATA_BYTES,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTE,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTES,
- ] {
- let mut bytes = hex_to_bytes(prefix.to_owned() + bytes_str);
- let result = trim_metadata(&mut bytes);
-
- assert_eq!(bytes, hex_to_bytes(prefix.into()));
- assert_eq!(result, 15);
- }
- }
-
- #[test]
- fn test_trim_payload() {
- let payload_hex = read_payload_bytes("./sample-data/payload.hex");
-
- let mut bytes = payload_hex[..payload_hex.len() - REDSTONE_MARKER_BS].into();
- let payload = trim_payload(&mut bytes);
-
- assert_eq!(bytes, Vec::<u8>::new());
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[test]
- fn test_make_payload() {
- let mut payload_hex = read_payload_bytes("./sample-data/payload.hex");
- let payload = Payload::make(&mut payload_hex);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[should_panic(expected = "Non empty payload remainder: 12")]
- #[test]
- fn test_make_payload_with_prefix() {
- let payload_hex = read_payload_hex("./sample-data/payload.hex");
- let mut bytes = hex_to_bytes("12".to_owned() + &payload_hex);
- let payload = Payload::make(&mut bytes);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-}
-
pub(crate) trait FilterSome<Output> {
- fn filter_some(&self) -> Output;
-}
-
-impl<T: Copy> FilterSome<Vec<T>> for [Option<T>] {
- fn filter_some(&self) -> Vec<T> {
- self.iter().filter_map(|&opt| opt).collect()
- }
-}
-
-#[cfg(test)]
-mod filter_some_tests {
- use crate::utils::filter::FilterSome;
-
- #[test]
- fn test_filter_some() {
- let values = [None, Some(23u64), None, Some(12), Some(12), None, Some(23)];
-
- assert_eq!(values.filter_some(), vec![23, 12, 12, 23])
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -
use crate::network::{assert::Assert, error::Error::ArrayIsEmpty, specific::U256};
-use std::ops::{Add, Rem, Shr};
-
-pub(crate) trait Median {
- type Item;
-
- fn median(self) -> Self::Item;
-}
-
-trait Avg {
- fn avg(self, other: Self) -> Self;
-}
-
-trait Averageable:
- Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy
-{
-}
-
-impl Averageable for i32 {}
-
-#[cfg(feature = "network_radix")]
-impl Avg for U256 {
- fn avg(self, other: Self) -> Self {
- let one = 1u32;
- let two = U256::from(2u8);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl Averageable for U256 {}
-
-impl<T> Avg for T
-where
- T: Averageable,
-{
- fn avg(self, other: Self) -> Self {
- let one = T::from(1);
- let two = T::from(2);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-impl<T> Median for Vec<T>
-where
- T: Copy + Ord + Avg,
-{
- type Item = T;
-
- fn median(self) -> Self::Item {
- let len = self.len();
-
- match len.assert_or_revert(|x| *x > 0, |_| ArrayIsEmpty) {
- 1 => self[0],
- 2 => self[0].avg(self[1]),
- 3 => maybe_pick_median(self[0], self[1], self[2]).unwrap_or_else(|| {
- maybe_pick_median(self[1], self[0], self[2])
- .unwrap_or_else(|| maybe_pick_median(self[1], self[2], self[0]).unwrap())
- }),
- _ => {
- let mut values = self;
- values.sort();
-
- let mid = len / 2;
-
- if len % 2 == 0 {
- values[mid - 1].avg(values[mid])
- } else {
- values[mid]
- }
- }
- }
- }
-}
-
-#[inline]
-fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>
-where
- T: PartialOrd,
-{
- if (b >= a && b <= c) || (b >= c && b <= a) {
- Some(b)
- } else {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{Avg, Median};
- use crate::network::specific::U256;
- use itertools::Itertools;
- use std::fmt::Debug;
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_avg() {
- let u256 = U256::max_value(); // 115792089237316195423570985008687907853269984665640564039457584007913129639935
- let u256_max_sub_1 = u256 - U256::from(1u32);
- let u256max_div_2 = u256 / U256::from(2u32);
-
- assert_eq!(u256.avg(U256::from(0u8)), u256max_div_2);
- assert_eq!(u256.avg(U256::from(1u8)), u256max_div_2 + U256::from(1u8));
- assert_eq!(u256.avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!(u256.avg(u256), u256);
-
- assert_eq!((u256_max_sub_1).avg(U256::from(0u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(U256::from(1u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!((u256_max_sub_1).avg(u256), u256_max_sub_1);
- }
-
- #[test]
- #[should_panic(expected = "Array is empty")]
- fn test_median_empty_vector() {
- let vec: Vec<i32> = vec![];
-
- vec.median();
- }
-
- #[test]
- fn test_median_single_element() {
- assert_eq!(vec![1].median(), 1);
- }
-
- #[test]
- fn test_median_two_elements() {
- test_all_permutations(vec![1, 3], 2);
- test_all_permutations(vec![1, 2], 1);
- test_all_permutations(vec![1, 1], 1);
- }
-
- #[test]
- fn test_median_three_elements() {
- test_all_permutations(vec![1, 2, 3], 2);
- test_all_permutations(vec![1, 1, 2], 1);
- test_all_permutations(vec![1, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1], 1);
- }
-
- #[test]
- fn test_median_even_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4], 2);
- test_all_permutations(vec![1, 2, 4, 4], 3);
- test_all_permutations(vec![1, 1, 3, 3], 2);
- test_all_permutations(vec![1, 1, 3, 4], 2);
- test_all_permutations(vec![1, 1, 1, 3], 1);
- test_all_permutations(vec![1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 1, 1, 1], 1);
- test_all_permutations(vec![1, 2, 3, 4, 5, 6], 3);
- }
-
- #[test]
- fn test_median_odd_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 1, 4, 5], 1);
- test_all_permutations(vec![1, 1, 1, 3, 3], 1);
- test_all_permutations(vec![1, 1, 3, 3, 5], 3);
-
- test_all_permutations(vec![1, 2, 3, 5, 5], 3);
- test_all_permutations(vec![1, 2, 5, 5, 5], 5);
- test_all_permutations(vec![1, 1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 3, 3, 5, 5], 3);
-
- test_all_permutations(vec![1, 2, 2, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1, 1, 2], 1);
- test_all_permutations(vec![1, 1, 1, 1, 1], 1);
-
- test_all_permutations(vec![1, 2, 3, 4, 5, 6, 7], 4);
- }
-
- fn test_all_permutations<T: Copy + Ord + Avg + Debug>(numbers: Vec<T>, expected_value: T) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
-
- for perm in perms {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- assert_eq!(p.median(), expected_value);
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -
use crate::network::{
- assert::Unwrap, error::Error, from_bytes_repr::FromBytesRepr, specific::U256,
-};
-
-pub trait Trim<T>
-where
- Self: Sized,
-{
- fn trim_end(&mut self, len: usize) -> T;
-}
-
-impl Trim<Vec<u8>> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> Self {
- if len >= self.len() {
- std::mem::take(self)
- } else {
- self.split_off(self.len() - len)
- }
- }
-}
-
-impl Trim<U256> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> U256 {
- U256::from_bytes_repr(self.trim_end(len))
- }
-}
-
-impl Trim<usize> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> usize {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-impl Trim<u64> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> u64 {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{
- network::specific::U256,
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
- };
-
- const MARKER_DECIMAL: u64 = 823907890102272;
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.into()
- }
-
- #[test]
- fn test_trim_end_number() {
- let (rest, result): (_, U256) = test_trim_end(3);
- assert_eq!(result, (256u32.pow(2) * 30).into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER[..6]);
-
- let (_, result): (_, u64) = test_trim_end(3);
- assert_eq!(result, 256u64.pow(2) * 30);
-
- let (_, result): (_, usize) = test_trim_end(3);
- assert_eq!(result, 256usize.pow(2) * 30);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(3);
- assert_eq!(result.as_slice(), &REDSTONE_MARKER[6..]);
- }
-
- #[test]
- fn test_trim_end_number_null() {
- let (rest, result): (_, U256) = test_trim_end(0);
- assert_eq!(result, 0u32.into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER);
-
- let (_, result): (_, u64) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, usize) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(0);
- assert_eq!(result, Vec::<u8>::new());
- }
-
- #[test]
- fn test_trim_end_whole() {
- test_trim_end_whole_size(REDSTONE_MARKER_BS);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 1);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 2);
- test_trim_end_whole_size(REDSTONE_MARKER_BS + 1);
- }
-
- fn test_trim_end_whole_size(size: usize) {
- let (rest, result): (_, U256) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL.into());
- assert_eq!(
- rest.as_slice().len(),
- REDSTONE_MARKER_BS - size.min(REDSTONE_MARKER_BS)
- );
-
- let (_, result): (_, u64) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL);
-
- let (_, result): (_, usize) = test_trim_end(size);
- assert_eq!(result, 823907890102272usize);
-
- let (_rest, result): (_, Vec<u8>) = test_trim_end(size);
- assert_eq!(result.as_slice().len(), size.min(REDSTONE_MARKER_BS));
- }
-
- #[test]
- fn test_trim_end_u64() {
- let mut bytes = vec![255, 255, 255, 255, 255, 255, 255, 255, 255];
- let x: u64 = bytes.trim_end(8);
-
- let expected_bytes = vec![255];
-
- assert_eq!(bytes, expected_bytes);
- assert_eq!(x, 18446744073709551615);
- }
-
- #[should_panic(expected = "Number overflow: 18591708106338011145")]
- #[test]
- fn test_trim_end_u64_overflow() {
- let mut bytes = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9];
-
- let _: u64 = bytes.trim_end(9);
- }
-
- #[allow(dead_code)]
- trait TestTrimEnd<T>
- where
- Self: Sized,
- {
- fn test_trim_end(size: usize) -> (Self, T);
- }
-
- fn test_trim_end<T>(size: usize) -> (Vec<u8>, T)
- where
- Vec<u8>: Trim<T>,
- {
- let mut bytes = redstone_marker_bytes();
- let rest = bytes.trim_end(size);
- (bytes, rest)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -
pub trait TrimZeros {
- fn trim_zeros(self) -> Self;
-}
-
-impl TrimZeros for Vec<u8> {
- fn trim_zeros(self) -> Self {
- let mut res = self.len();
-
- for i in (0..self.len()).rev() {
- if self[i] != 0 {
- break;
- }
-
- res = i;
- }
-
- let (rest, _) = self.split_at(res);
-
- rest.into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{protocol::constants::REDSTONE_MARKER, utils::trim_zeros::TrimZeros};
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.as_slice().into()
- }
-
- #[test]
- fn test_trim_zeros() {
- let trimmed = redstone_marker_bytes().trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
-
- let trimmed = trimmed.trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
- }
-
- #[test]
- fn test_trim_zeros_empty() {
- let trimmed = Vec::<u8>::default().trim_zeros();
- assert_eq!(trimmed, Vec::<u8>::default());
- }
-}
-
fn:
) to \
- restrict the search to a given item kind.","Accepted kinds are: fn
, mod
, struct
, \
- enum
, trait
, type
, macro
, \
- and const
.","Search functions by type signature (e.g., vec -> usize
or \
- -> vec
or String, enum:Cow -> bool
)","You can look for items with an exact name by putting double quotes around \
- your request: \"string\"
","Look for functions that accept or return \
- slices and \
- arrays by writing \
- square brackets (e.g., -> [u8]
or [] -> Option
)","Look for items inside another one by searching for a path: vec::Vec
",].map(x=>""+x+"
").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="${value.replaceAll(" ", " ")}
`}else{error[index]=value}});output+=`Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,\nas it avoids reallocation if possible. Additionally, if the element type\nT
overrides clone_from()
, this will reuse the resources of self
’s\nelements as well.
let x = vec![5, 6, 7];\nlet mut y = vec![8, 9, 10];\nlet yp: *const i32 = y.as_ptr();\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no reallocation occurred\nassert_eq!(yp, y.as_ptr());
Extend implementation that copies elements out of references before pushing them onto the Vec.
\nThis implementation is specialized for slice iterators, where it uses copy_from_slice
to\nappend the entire slice at once.
extend_one
)extend_one
)extend_one
)extend_one
)Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has\nconstant time complexity.
\nConvert a clone-on-write slice into a vector.
\nIf s
already owns a Vec<T>
, it will be returned directly.\nIf s
is borrowing a slice, a new Vec<T>
will be allocated and\nfilled by cloning s
’s items into it.
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);\nlet b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);\nassert_eq!(Vec::from(o), Vec::from(b));
Turn a VecDeque<T>
into a Vec<T>
.
This never needs to re-allocate, but does need to do O(n) data movement if\nthe circular buffer doesn’t happen to be at the beginning of the allocation.
\nuse std::collections::VecDeque;\n\n// This one is *O*(1).\nlet deque: VecDeque<_> = (1..5).collect();\nlet ptr = deque.as_slices().0.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);\n\n// This one needs data rearranging.\nlet mut deque: VecDeque<_> = (1..5).collect();\ndeque.push_front(9);\ndeque.push_front(8);\nlet ptr = deque.as_slices().1.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [8, 9, 1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);
Collects an iterator into a Vec, commonly called via Iterator::collect()
In general Vec
does not guarantee any particular growth or allocation strategy.\nThat also applies to this trait impl.
Note: This section covers implementation details and is therefore exempt from\nstability guarantees.
\nVec may use any or none of the following strategies,\ndepending on the supplied iterator:
\nIterator::size_hint()
\npushing
one item at a timeThe last case warrants some attention. It is an optimization that in many cases reduces peak memory\nconsumption and improves cache locality. But when big, short-lived allocations are created,\nonly a small fraction of their items get collected, no further use is made of the spare capacity\nand the resulting Vec
is moved into a longer-lived structure, then this can lead to the large\nallocations having their lifetimes unnecessarily extended which can result in increased memory\nfootprint.
In cases where this is an issue, the excess capacity can be discarded with Vec::shrink_to()
,\nVec::shrink_to_fit()
or by collecting into Box<[T]>
instead, which additionally reduces\nthe size of the long-lived struct.
static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());\n\nfor i in 0..10 {\n let big_temporary: Vec<u16> = (0..1024).collect();\n // discard most items\n let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();\n // without this a lot of unused capacity might be moved into the global\n result.shrink_to_fit();\n LONG_LIVED.lock().unwrap().push(result);\n}
The hash of a vector is the same as that of the corresponding slice,\nas required by the core::borrow::Borrow
implementation.
use std::hash::BuildHasher;\n\nlet b = std::hash::RandomState::new();\nlet v: Vec<u8> = vec![0xa8, 0x3c, 0x09];\nlet s: &[u8] = &[0xa8, 0x3c, 0x09];\nassert_eq!(b.hash_one(v), b.hash_one(s));
Creates a consuming iterator, that is, one that moves each value out of\nthe vector (from start to end). The vector cannot be used after calling\nthis.
\nlet v = vec![\"a\".to_string(), \"b\".to_string()];\nlet mut v_iter = v.into_iter();\n\nlet first_element: Option<String> = v_iter.next();\n\nassert_eq!(first_element, Some(\"a\".to_string()));\nassert_eq!(v_iter.next(), Some(\"b\".to_string()));\nassert_eq!(v_iter.next(), None);
Implements ordering of vectors, lexicographically.
\nImplements comparison of vectors, lexicographically.
\nself
and other
) and is used by the <=
\noperator. Read moreVec<u8>
which would be returned from a successful call to\nto_bytes()
or into_bytes()
. The data is not actually serialized, so this call is\nrelatively cheap.Constructs a new, empty Vec<T>
.
The vector will not allocate until elements are pushed onto it.
\nlet mut vec: Vec<i32> = Vec::new();
Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = Vec::with_capacity(10);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<()>::with_capacity(10);\nassert_eq!(vec_units.capacity(), usize::MAX);
try_with_capacity
)Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
Creates a Vec<T>
directly from a pointer, a length, and a capacity.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must have been allocated using the global allocator, such as via\nthe alloc::alloc
function.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to be the capacity that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is normally not safe\nto build a Vec<u8>
from a pointer to a C char
array with length\nsize_t
, doing so is only safe if the array was initially allocated by\na Vec
or String
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid\nthese issues, it is often preferable to do casting/transmuting using\nslice::from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
use std::ptr;\nuse std::mem;\n\nlet v = vec![1, 2, 3];\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts(p, len, cap);\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\nuse std::alloc::{alloc, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = alloc(layout).cast::<u32>();\n if mem.is_null() {\n return;\n }\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts(mem, 1, 16)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with value
.\nIf new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,\nin order to be able to clone the passed value.\nIf you need more flexibility (or want to rely on Default
instead of\nClone
), use Vec::resize_with
.\nIf you only need to resize to a smaller size, use Vec::truncate
.
let mut vec = vec![\"hello\"];\nvec.resize(3, \"world\");\nassert_eq!(vec, [\"hello\", \"world\", \"world\"]);\n\nlet mut vec = vec![1, 2, 3, 4];\nvec.resize(2, 0);\nassert_eq!(vec, [1, 2]);
Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends\nit to this Vec
. The other
slice is traversed in-order.
Note that this function is same as extend
except that it is\nspecialized to work with slices instead. If and when Rust gets\nspecialization this function will likely be deprecated (but still\navailable).
let mut vec = vec![1];\nvec.extend_from_slice(&[2, 3, 4]);\nassert_eq!(vec, [1, 2, 3, 4]);
Copies elements from src
range to the end of the vector.
Panics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut vec = vec![0, 1, 2, 3, 4];\n\nvec.extend_from_within(2..);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);\n\nvec.extend_from_within(..2);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);\n\nvec.extend_from_within(4..8);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
Creates a splicing iterator that replaces the specified range in the vector\nwith the given replace_with
iterator and yields the removed items.\nreplace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many elements are removed from the vector\nif the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
\nrange
) is empty,replace_with
yields fewer or equal elements than range
’s lengthsize_hint()
is exact.Otherwise, a temporary vector is allocated and the tail is moved twice.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut v = vec![1, 2, 3, 4];\nlet new = [7, 8, 9];\nlet u: Vec<_> = v.splice(1..3, new).collect();\nassert_eq!(v, &[1, 7, 8, 9, 4]);\nassert_eq!(u, &[2, 3]);
extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, then the element is removed and yielded.\nIf the closure returns false, the element will remain in the vector and will not be yielded\nby the iterator.
\nIf the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
\n\nlet mut i = 0;\nwhile i < vec.len() {\n if some_predicate(&mut vec[i]) {\n let val = vec.remove(i);\n // your code here\n } else {\n i += 1;\n }\n}\n
But extract_if
is easier to use. extract_if
is also more efficient,\nbecause it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate every element in the filter closure,\nregardless of whether you choose to keep or remove it.
Splitting an array into evens and odds, reusing the original allocation:
\n\n#![feature(extract_if)]\nlet mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];\n\nlet evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();\nlet odds = numbers;\n\nassert_eq!(evens, vec![2, 4, 6, 8, 14]);\nassert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
allocator_api
)Constructs a new, empty Vec<T, A>
.
The vector will not allocate until elements are pushed onto it.
\n#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec: Vec<i32, _> = Vec::new_in(System);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T, A>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec = Vec::with_capacity_in(10, System);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<(), System>::with_capacity_in(10, System);\nassert_eq!(vec_units.capacity(), usize::MAX);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
allocator_api
)Creates a Vec<T, A>
directly from a pointer, a length, a capacity,\nand an allocator.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must be currently allocated via the given allocator alloc
.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to fit the layout size that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T, A>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is not safe\nto build a Vec<u8>
from a pointer to a C char
array with length size_t
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nuse std::ptr;\nuse std::mem;\n\nlet mut v = Vec::with_capacity_in(3, System);\nv.push(1);\nv.push(2);\nv.push(3);\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\nlet alloc = v.allocator();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\n#![feature(allocator_api)]\n\nuse std::alloc::{AllocError, Allocator, Global, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = match Global.allocate(layout) {\n Ok(mem) => mem.cast::<u32>().as_ptr(),\n Err(AllocError) => return,\n };\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts_in(mem, 1, 16, Global)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
vec_into_raw_parts
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity)
.
Returns the raw pointer to the underlying data, the length of\nthe vector (in elements), and the allocated capacity of the\ndata (in elements). These are the same arguments in the same\norder as the arguments to from_raw_parts
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts
function, allowing\nthe destructor to perform the cleanup.
#![feature(vec_into_raw_parts)]\nlet v: Vec<i32> = vec![-1, 0, 1];\n\nlet (ptr, len, cap) = v.into_raw_parts();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts(ptr, len, cap)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
allocator_api
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity, allocator)
.
Returns the raw pointer to the underlying data, the length of the vector (in elements),\nthe allocated capacity of the data (in elements), and the allocator. These are the same\narguments in the same order as the arguments to from_raw_parts_in
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts_in
function, allowing\nthe destructor to perform the cleanup.
#![feature(allocator_api, vec_into_raw_parts)]\n\nuse std::alloc::System;\n\nlet mut v: Vec<i32, System> = Vec::new_in(System);\nv.push(-1);\nv.push(0);\nv.push(1);\n\nlet (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts_in(ptr, len, cap, alloc)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
Returns the total number of elements the vector can hold without\nreallocating.
\nlet mut vec: Vec<i32> = Vec::with_capacity(10);\nvec.push(42);\nassert!(vec.capacity() >= 10);
Reserves capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to\nspeculatively avoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve(10);\nassert!(vec.capacity() >= 11);
Reserves the minimum capacity for at least additional
more elements to\nbe inserted in the given Vec<T>
. Unlike reserve
, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact
, capacity will be greater than or equal to\nself.len() + additional
. Does nothing if the capacity is already\nsufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer reserve
if future insertions are expected.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve_exact(10);\nassert!(vec.capacity() >= 11);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to speculatively avoid\nfrequent reallocations. After calling try_reserve
, capacity will be\ngreater than or equal to self.len() + additional
if it returns\nOk(())
. Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Tries to reserve the minimum capacity for at least additional
\nelements to be inserted in the given Vec<T>
. Unlike try_reserve
,\nthis will not deliberately over-allocate to speculatively avoid frequent\nallocations. After calling try_reserve_exact
, capacity will be greater\nthan or equal to self.len() + additional
if it returns Ok(())
.\nDoes nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve
if future insertions are expected.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve_exact(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Shrinks the capacity of the vector as much as possible.
\nThe behavior of this method depends on the allocator, which may either shrink the vector\nin-place or reallocate. The resulting vector might still have some excess capacity, just as\nis the case for with_capacity
. See Allocator::shrink
for more details.
let mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to_fit();\nassert!(vec.capacity() >= 3);
Shrinks the capacity of the vector with a lower bound.
\nThe capacity will remain at least as large as both the length\nand the supplied value.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to(4);\nassert!(vec.capacity() >= 4);\nvec.shrink_to(0);\nassert!(vec.capacity() >= 3);
Converts the vector into Box<[T]>
.
Before doing the conversion, this method discards excess capacity like shrink_to_fit
.
let v = vec![1, 2, 3];\n\nlet slice = v.into_boxed_slice();
Any excess capacity is removed:
\n\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\n\nassert!(vec.capacity() >= 10);\nlet slice = vec.into_boxed_slice();\nassert_eq!(slice.into_vec().capacity(), 3);
Shortens the vector, keeping the first len
elements and dropping\nthe rest.
If len
is greater or equal to the vector’s current length, this has\nno effect.
The drain
method can emulate truncate
, but causes the excess\nelements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity\nof the vector.
\nTruncating a five element vector to two elements:
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nvec.truncate(2);\nassert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current\nlength:
let mut vec = vec![1, 2, 3];\nvec.truncate(8);\nassert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
\nmethod.
let mut vec = vec![1, 2, 3];\nvec.truncate(0);\nassert_eq!(vec, []);
Extracts a slice containing the entire vector.
\nEquivalent to &s[..]
.
use std::io::{self, Write};\nlet buffer = vec![1, 2, 3, 5, 8];\nio::sink().write(buffer.as_slice()).unwrap();
Extracts a mutable slice of the entire vector.
\nEquivalent to &mut s[..]
.
use std::io::{self, Read};\nlet mut buffer = vec![0; 3];\nio::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer\nvalid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThe caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell
) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize mutable references to the slice,\nor mutable references to specific elements you are planning on accessing through this pointer,\nas well as writing to those elements, may still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
let x = vec![1, 2, 4];\nlet x_ptr = x.as_ptr();\n\nunsafe {\n for i in 0..x.len() {\n assert_eq!(*x_ptr.add(i), 1 << i);\n }\n}
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0, 1, 2];\n let ptr1 = v.as_ptr();\n let _ = ptr1.read();\n let ptr2 = v.as_mut_ptr().offset(2);\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`\n // because it mutated a different element:\n let _ = ptr1.read();\n}
Returns an unsafe mutable pointer to the vector’s buffer, or a dangling\nraw pointer valid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThis method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize references to the slice,\nor references to specific elements you are planning on accessing through this pointer,\nmay still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
// Allocate vector big enough for 4 elements.\nlet size = 4;\nlet mut x: Vec<i32> = Vec::with_capacity(size);\nlet x_ptr = x.as_mut_ptr();\n\n// Initialize elements via raw pointer writes, then set length.\nunsafe {\n for i in 0..size {\n *x_ptr.add(i) = i as i32;\n }\n x.set_len(size);\n}\nassert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0];\n let ptr1 = v.as_mut_ptr();\n ptr1.write(1);\n let ptr2 = v.as_mut_ptr();\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`:\n ptr1.write(3);\n}
allocator_api
)Returns a reference to the underlying allocator.
\nForces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal\ninvariants of the type. Normally changing the length of a vector\nis done using one of the safe operations instead, such as\ntruncate
, resize
, extend
, or clear
.
new_len
must be less than or equal to capacity()
.old_len..new_len
must be initialized.This method can be useful for situations in which the vector\nis serving as a buffer for other code, particularly over FFI:
\n\npub fn get_dictionary(&self) -> Option<Vec<u8>> {\n // Per the FFI method's docs, \"32768 bytes is always enough\".\n let mut dict = Vec::with_capacity(32_768);\n let mut dict_length = 0;\n // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:\n // 1. `dict_length` elements were initialized.\n // 2. `dict_length` <= the capacity (32_768)\n // which makes `set_len` safe to call.\n unsafe {\n // Make the FFI call...\n let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);\n if r == Z_OK {\n // ...and update the length to what was initialized.\n dict.set_len(dict_length);\n Some(dict)\n } else {\n None\n }\n }\n}
While the following example is sound, there is a memory leak since\nthe inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],\n vec![0, 1, 0],\n vec![0, 0, 1]];\n// SAFETY:\n// 1. `old_len..0` is empty so no elements need to be initialized.\n// 2. `0 <= capacity` always holds whatever `capacity` is.\nunsafe {\n vec.set_len(0);\n}
Normally, here, one would use clear
instead to correctly drop\nthe contents and thus not leak memory.
Removes an element from the vector and returns it.
\nThe removed element is replaced by the last element of the vector.
\nThis does not preserve ordering of the remaining elements, but is O(1).\nIf you need to preserve the element order, use remove
instead.
Panics if index
is out of bounds.
let mut v = vec![\"foo\", \"bar\", \"baz\", \"qux\"];\n\nassert_eq!(v.swap_remove(1), \"bar\");\nassert_eq!(v, [\"foo\", \"qux\", \"baz\"]);\n\nassert_eq!(v.swap_remove(0), \"foo\");\nassert_eq!(v, [\"baz\", \"qux\"]);
Inserts an element at position index
within the vector, shifting all\nelements after it to the right.
Panics if index > len
.
let mut vec = vec![1, 2, 3];\nvec.insert(1, 4);\nassert_eq!(vec, [1, 4, 2, 3]);\nvec.insert(4, 5);\nassert_eq!(vec, [1, 4, 2, 3, 5]);
Takes O(Vec::len
) time. All items after the insertion index must be\nshifted to the right. In the worst case, all elements are shifted when\nthe insertion index is 0.
Removes and returns the element at position index
within the vector,\nshifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a\nworst-case performance of O(n). If you don’t need the order of elements\nto be preserved, use swap_remove
instead. If you’d like to remove\nelements from the beginning of the Vec
, consider using\nVecDeque::pop_front
instead.
Panics if index
is out of bounds.
let mut v = vec![1, 2, 3];\nassert_eq!(v.remove(1), 2);\nassert_eq!(v, [1, 3]);
Retains only the elements specified by the predicate.
\nIn other words, remove all elements e
for which f(&e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain(|&x| x % 2 == 0);\nassert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\nvec.retain(|_| *iter.next().unwrap());\nassert_eq!(vec, [2, 3, 5]);
Retains only the elements specified by the predicate, passing a mutable reference to it.
\nIn other words, remove all elements e
such that f(&mut e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain_mut(|x| if *x <= 3 {\n *x += 1;\n true\n} else {\n false\n});\nassert_eq!(vec, [2, 3, 4]);
Removes all but the first of consecutive elements in the vector that resolve to the same\nkey.
\nIf the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![10, 20, 21, 30, 20];\n\nvec.dedup_by_key(|i| *i / 10);\n\nassert_eq!(vec, [10, 20, 30, 20]);
Removes all but the first of consecutive elements in the vector satisfying a given equality\nrelation.
\nThe same_bucket
function is passed references to two elements from the vector and\nmust determine if the elements compare equal. The elements are passed in opposite order\nfrom their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![\"foo\", \"bar\", \"Bar\", \"baz\", \"bar\"];\n\nvec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));\n\nassert_eq!(vec, [\"foo\", \"bar\", \"baz\", \"bar\"]);
Appends an element to the back of a collection.
\nPanics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1, 2];\nvec.push(3);\nassert_eq!(vec, [1, 2, 3]);
Takes amortized O(1) time. If the vector’s length would exceed its\ncapacity after the push, O(capacity) time is taken to copy the\nvector’s elements to a larger allocation. This expensive operation is\noffset by the capacity O(1) insertions it allows.
\nvec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned\nwith the element.
\nUnlike push
this method will not reallocate when there’s insufficient capacity.\nThe caller should use reserve
or try_reserve
to ensure that there is enough capacity.
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]\n\nuse std::collections::TryReserveError;\nfn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {\n let mut vec = Vec::new();\n for value in iter {\n if let Err(value) = vec.push_within_capacity(value) {\n vec.try_reserve(1)?;\n // this cannot fail, the previous line either returned or added at least 1 free slot\n let _ = vec.push_within_capacity(value);\n }\n }\n Ok(vec)\n}\nassert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
Takes O(1) time.
\nRemoves the last element from a vector and returns it, or None
if it\nis empty.
If you’d like to pop the first element, consider using\nVecDeque::pop_front
instead.
let mut vec = vec![1, 2, 3];\nassert_eq!(vec.pop(), Some(3));\nassert_eq!(vec, [1, 2]);
Takes O(1) time.
\nvec_pop_if
)Removes and returns the last element in a vector if the predicate\nreturns true
, or None
if the predicate returns false or the vector\nis empty.
#![feature(vec_pop_if)]\n\nlet mut vec = vec![1, 2, 3, 4];\nlet pred = |x: &mut i32| *x % 2 == 0;\n\nassert_eq!(vec.pop_if(pred), Some(4));\nassert_eq!(vec, [1, 2, 3]);\nassert_eq!(vec.pop_if(pred), None);
Removes the specified range from the vector in bulk, returning all\nremoved elements as an iterator. If the iterator is dropped before\nbeing fully consumed, it drops the remaining removed elements.
\nThe returned iterator keeps a mutable borrow on the vector to optimize\nits implementation.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nIf the returned iterator goes out of scope without being dropped (due to\nmem::forget
, for example), the vector may have lost and leaked\nelements arbitrarily, including elements outside the range.
let mut v = vec![1, 2, 3];\nlet u: Vec<_> = v.drain(1..).collect();\nassert_eq!(v, &[1]);\nassert_eq!(u, &[2, 3]);\n\n// A full range clears the vector, like `clear()` does\nv.drain(..);\nassert_eq!(v, &[]);
Clears the vector, removing all values.
\nNote that this method has no effect on the allocated capacity\nof the vector.
\nlet mut v = vec![1, 2, 3];\n\nv.clear();\n\nassert!(v.is_empty());
Returns the number of elements in the vector, also referred to\nas its ‘length’.
\nlet a = vec![1, 2, 3];\nassert_eq!(a.len(), 3);
Returns true
if the vector contains no elements.
let mut v = Vec::new();\nassert!(v.is_empty());\n\nv.push(1);\nassert!(!v.is_empty());
Splits the collection into two at the given index.
\nReturns a newly allocated vector containing the elements in the range\n[at, len)
. After the call, the original vector will be left containing\nthe elements [0, at)
with its previous capacity unchanged.
mem::take
or mem::replace
.Vec::truncate
.Vec::drain
.Panics if at > len
.
let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with the result of\ncalling the closure f
. The return values from f
will end up\nin the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If\nyou’d rather Clone
a given value, use Vec::resize
. If you\nwant to use the Default
trait to generate values, you can\npass Default::default
as the second argument.
let mut vec = vec![1, 2, 3];\nvec.resize_with(5, Default::default);\nassert_eq!(vec, [1, 2, 3, 0, 0]);\n\nlet mut vec = vec![];\nlet mut p = 1;\nvec.resize_with(4, || { p *= 2; p });\nassert_eq!(vec, [2, 4, 8, 16]);
Consumes and leaks the Vec
, returning a mutable reference to the contents,\n&'a mut [T]
. Note that the type T
must outlive the chosen lifetime\n'a
. If the type has only static references, or none at all, then this\nmay be chosen to be 'static
.
As of Rust 1.57, this method does not reallocate or shrink the Vec
,\nso the leaked allocation may include unused capacity that is not part\nof the returned slice.
This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak.
\nSimple usage:
\n\nlet x = vec![1, 2, 3];\nlet static_ref: &'static mut [usize] = x.leak();\nstatic_ref[0] += 1;\nassert_eq!(static_ref, &[2, 2, 3]);
Returns the remaining spare capacity of the vector as a slice of\nMaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by\nreading from a file) before marking the data as initialized using the\nset_len
method.
// Allocate vector big enough for 10 elements.\nlet mut v = Vec::with_capacity(10);\n\n// Fill in the first 3 elements.\nlet uninit = v.spare_capacity_mut();\nuninit[0].write(0);\nuninit[1].write(1);\nuninit[2].write(2);\n\n// Mark the first 3 elements of the vector as being initialized.\nunsafe {\n v.set_len(3);\n}\n\nassert_eq!(&v, &[0, 1, 2]);
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare\ncapacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data\n(e.g. by reading from a file) before marking the data as initialized using\nthe set_len
method.
Note that this is a low-level API, which should be used with care for\noptimization purposes. If you need to append data to a Vec
\nyou can use push
, extend
, extend_from_slice
,\nextend_from_within
, insert
, append
, resize
or\nresize_with
, depending on your exact needs.
#![feature(vec_split_at_spare)]\n\nlet mut v = vec![1, 1, 2];\n\n// Reserve additional space big enough for 10 elements.\nv.reserve(10);\n\nlet (init, uninit) = v.split_at_spare_mut();\nlet sum = init.iter().copied().sum::<u32>();\n\n// Fill in the next 4 elements.\nuninit[0].write(sum);\nuninit[1].write(sum * 2);\nuninit[2].write(sum * 3);\nuninit[3].write(sum * 4);\n\n// Mark the 4 elements of the vector as being initialized.\nunsafe {\n let len = v.len();\n v.set_len(len + 4);\n}\n\nassert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
pub(crate) fn aggregate_values(
- config: Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<U256>
Aggregates values from a collection of data packages according to the provided configuration.
-This function takes a configuration and a vector of data packages, constructs a matrix of values
-and their corresponding signers, and then aggregates these values based on the aggregation logic
-defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-an average of the values, selecting the median, or applying a custom algorithm defined within the
-aggregate_matrix
function.
The primary purpose of this function is to consolidate data from multiple sources into a coherent
-and singular value set that adheres to the criteria specified in the Config
.
config
- A Config
instance containing settings and parameters used to guide the aggregation process.data_packages
- A vector of DataPackage
instances, each representing a set of values and associated
-metadata collected from various sources or signers.Returns a Vec<U256>
, which is a vector of aggregated values resulting from applying the aggregation
-logic to the input data packages as per the specified configuration. Each U256
value in the vector
-represents an aggregated result derived from the corresponding data packages.
This function is internal to the crate (pub(crate)
) and not exposed as part of the public API. It is
-designed to be used by other components within the same crate that require value aggregation functionality.
fn make_value_signer_matrix(
- config: &Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<Vec<Option<U256>>>
pub struct Config {
- pub signer_count_threshold: u8,
- pub signers: Vec<Bytes>,
- pub feed_ids: Vec<U256>,
- pub block_timestamp: u64,
-}
Configuration for a RedStone payload processor.
-Specifies the parameters necessary for the verification and aggregation of values -from various data points passed by the RedStone payload.
-signer_count_threshold: u8
The minimum number of signers required validating the data.
-Specifies how many unique signers (from different addresses) are required -for the data to be considered valid and trustworthy.
-signers: Vec<Bytes>
List of identifiers for signers authorized to sign the data.
-Each signer is identified by a unique, network-specific byte string (Bytes
),
-which represents their address.
feed_ids: Vec<U256>
Identifiers for the data feeds from which values are aggregated.
-Each data feed id is represented by the network-specific U256
type.
block_timestamp: u64
The current block time in timestamp format, used for verifying data timeliness.
-The value’s been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows -for determining whether the data is current in the context of blockchain time.
-self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morefn make_processor_result(config: Config, payload: Payload) -> ProcessorResult
pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult
The main processor of the RedStone payload.
-config
- Configuration of the payload processing.payload_bytes
- Network-specific byte-list of the payload to be processed.pub struct ProcessorResult {
- pub min_timestamp: u64,
- pub values: Vec<U256>,
-}
Represents the result of processing the RedStone payload.
-This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-particularly focusing on time-sensitive data and its associated values, according to the Config
.
min_timestamp: u64
The minimum timestamp encountered during processing.
-This field captures the earliest time point (in milliseconds since the Unix epoch) -among the processed data packages, indicating the starting boundary of the dataset’s time range.
-values: Vec<U256>
A collection of values processed during the operation.
-Each element in this vector represents a processed value corresponding
-to the passed data_feed item in the Config
.
self
and other
values to be equal, and is used
-by ==
.self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.pub(crate) trait Validator {
- // Required methods
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
- fn validate_signer_count_threshold(
- &self,
- index: usize,
- values: &[Option<U256>],
- ) -> Vec<U256>;
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
A trait defining validation operations for data feeds and signers.
-This trait specifies methods for validating aspects of data feeds and signers within a system that -requires data integrity and authenticity checks. Implementations of this trait are responsible for -defining the logic behind each validation step, ensuring that data conforms to expected rules and -conditions.
-Retrieves the index of a given data feed.
-This method takes a feed_id
representing the unique identifier of a data feed and
-returns an Option<usize>
indicating the index of the feed within a collection of feeds.
-If the feed does not exist, None
is returned.
feed_id
: U256
- The unique identifier of the data feed.Option<usize>
- The index of the feed if it exists, or None
if it does not.Retrieves the index of a given signer.
-This method accepts a signer identifier in the form of a byte slice and returns an
-Option<usize>
indicating the signer’s index within a collection of signers. If the signer
-is not found, None
is returned.
signer
: &[u8]
- A byte slice representing the signer’s identifier.Option<usize>
- The index of the signer if found, or None
if not found.Validates the signer count threshold for a given index within a set of values.
-This method is responsible for ensuring that the number of valid signers meets or exceeds
-a specified threshold necessary for a set of data values to be considered valid. It returns
-a vector of U256
if the values pass the validation, to be processed in other steps.
index
: usize
- The index of the data value being validated.values
: &[Option<U256>]
- A slice of optional U256
values associated with the data.Vec<U256>
- A vector of U256
values that meet the validation criteria.Validates the timestamp for a given index.
-This method checks whether a timestamp associated with a data value at a given index -meets specific conditions (e.g., being within an acceptable time range). It returns -the validated timestamp if it’s valid, to be processed in other steps.
-index
: usize
- The index of the data value whose timestamp is being validated.timestamp
: u64
- The timestamp to be validated.u64
- The validated timestamp.redstone
is a collection of utilities to make deserializing&decrypting RedStone payload.
-It contains a pure Rust implementation and also an extension for some networks.
Different crypto-mechanisms are easily injectable.
-The current implementation contains secp256k1
- and k256
-based variants.
Redirecting to macro.print_and_panic.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_and_panic.html b/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_and_panic.html deleted file mode 100644 index b308eb68..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_and_panic.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_and_panic { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
Redirecting to macro.print_debug.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_debug.html b/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_debug.html deleted file mode 100644 index 3cb863d6..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_radix/doc/redstone/macro.print_debug.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_debug { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
pub trait AsAsciiStr {
- // Required method
- fn as_ascii_str(&self) -> String;
-}
pub trait AsHexStr {
- // Required method
- fn as_hex_str(&self) -> String;
-}
pub trait Assert<F> {
- // Required method
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
pub trait Unwrap<R> {
- type ErrorArg;
-
- // Required method
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
pub enum Error {
- ContractError(Box<dyn ContractErrorContent>),
- NumberOverflow(U256),
- ArrayIsEmpty,
- CryptographicError(usize),
- SizeNotSupported(usize),
- WrongRedStoneMarker(Vec<u8>),
- NonEmptyPayloadRemainder(Vec<u8>),
- InsufficientSignerCount(usize, usize, U256),
- TimestampTooOld(usize, u64),
- TimestampTooFuture(usize, u64),
- ClonedContractError(u8, String),
-}
Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-These errors include issues with contract logic, data types, -cryptographic operations, and conditions specific to the requirements.
-Represents errors that arise from the contract itself.
-This variant is used for encapsulating errors that are specific to the contract’s logic -or execution conditions that aren’t covered by more specific error types.
-Indicates an overflow error with U256
numbers.
Used when operations on U256
numbers exceed their maximum value, potentially leading
-to incorrect calculations or state.
Used when an expected non-empty array or vector is found to be empty.
-This could occur in scenarios where the contract logic requires a non-empty collection -of items for the correct operation, for example, during aggregating the values.
-Represents errors related to cryptographic operations.
-This includes failures in signature verification, hashing, or other cryptographic -processes, with the usize indicating the position or identifier of the failed operation.
-Signifies that an unsupported size was encountered.
-This could be used when a data structure or input does not meet the expected size -requirements for processing.
-Indicates that the marker bytes for RedStone are incorrect.
-This error is specific to scenarios where marker or identifier bytes do not match -expected values, potentially indicating corrupted or tampered data.
-Used when there is leftover data in a payload that should have been empty.
-This could indicate an error in data parsing or that additional, unexpected data -was included in a message or transaction.
-Indicates that the number of signers does not meet the required threshold.
-This variant includes the current number of signers, the required threshold, and -potentially a feed_id related to the operation that failed due to insufficient signers.
-Used when a timestamp is older than allowed by the processor logic.
-Includes the position or identifier of the timestamp and the threshold value, -indicating that the provided timestamp is too far in the past.
-Indicates that a timestamp is further in the future than allowed.
-Similar to TimestampTooOld
, but for future timestamps exceeding the contract’s
-acceptance window.
Represents errors that need to clone ContractErrorContent
, which is not supported by default.
This variant allows for the manual duplication of contract error information, including -an error code and a descriptive message.
-self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub trait FromBytesRepr<T> {
- // Required method
- fn from_bytes_repr(bytes: T) -> Self;
-}
pub struct Radix;
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- // Required methods
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage
pub(crate) fn trim_data_packages(
- payload: &mut Vec<u8>,
- count: usize,
-) -> Vec<DataPackage>
pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
signer_address: Vec<u8>
§timestamp: u64
§data_points: Vec<DataPoint>
source
. Read moreself
and other
values to be equal, and is used
-by ==
.self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint
pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
feed_id: U256
§value: U256
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
data_packages: Vec<DataPackage>
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub(crate) trait FilterSome<Output> {
- // Required method
- fn filter_some(&self) -> Output;
-}
fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>where
- T: PartialOrd,
pub trait TrimZeros {
- // Required method
- fn trim_zeros(self) -> Self;
-}
U::from(self)
.\nThe minimum number of signers required validating the data.\nList of identifiers for signers authorized to sign the …\nThe main processor of the RedStone payload.\nRepresents the result of processing the RedStone payload.\nReturns the argument unchanged.\nCalls U::from(self)
.\nThe minimum timestamp encountered during processing.\nA collection of values processed during the operation.\nA trait defining validation operations for data feeds and …\nRetrieves the index of a given data feed.\nRetrieves the index of a given signer.\nValidates the signer count threshold for a given index …\nValidates the timestamp for a given index.\nUsed when an expected non-empty array or vector is found …\nRepresents errors that need to clone ContractErrorContent
, …\nRepresents errors that arise from the contract itself.\nRepresents errors related to cryptographic operations.\nErrors that can be encountered in the …\nIndicates that the number of signers does not meet the …\nUsed when there is leftover data in a payload that should …\nIndicates an overflow error with U256
numbers.\nSignifies that an unsupported size was encountered.\nIndicates that a timestamp is further in the future than …\nUsed when a timestamp is older than allowed by the …\nIndicates that the marker bytes for RedStone are incorrect.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.")
\ No newline at end of file
diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/doc/settings.html b/static/rust/redstone/crypto_secp256k1,network_radix/doc/settings.html
deleted file mode 100644
index 9631dcb2..00000000
--- a/static/rust/redstone/crypto_secp256k1,network_radix/doc/settings.html
+++ /dev/null
@@ -1 +0,0 @@
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -
use crate::{
- core::{config::Config, validator::Validator},
- network::specific::U256,
- print_debug,
- protocol::data_package::DataPackage,
- utils::median::Median,
-};
-
-type Matrix = Vec<Vec<Option<U256>>>;
-
-/// Aggregates values from a collection of data packages according to the provided configuration.
-///
-/// This function takes a configuration and a vector of data packages, constructs a matrix of values
-/// and their corresponding signers, and then aggregates these values based on the aggregation logic
-/// defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-/// an average of the values, selecting the median, or applying a custom algorithm defined within the
-/// `aggregate_matrix` function.
-///
-/// The primary purpose of this function is to consolidate data from multiple sources into a coherent
-/// and singular value set that adheres to the criteria specified in the `Config`.
-///
-/// # Arguments
-///
-/// * `config` - A `Config` instance containing settings and parameters used to guide the aggregation process.
-/// * `data_packages` - A vector of `DataPackage` instances, each representing a set of values and associated
-/// metadata collected from various sources or signers.
-///
-/// # Returns
-///
-/// Returns a `Vec<U256>`, which is a vector of aggregated values resulting from applying the aggregation
-/// logic to the input data packages as per the specified configuration. Each `U256` value in the vector
-/// represents an aggregated result derived from the corresponding data packages.
-///
-/// # Note
-///
-/// This function is internal to the crate (`pub(crate)`) and not exposed as part of the public API. It is
-/// designed to be used by other components within the same crate that require value aggregation functionality.
-pub(crate) fn aggregate_values(config: Config, data_packages: Vec<DataPackage>) -> Vec<U256> {
- aggregate_matrix(make_value_signer_matrix(&config, data_packages), config)
-}
-
-fn aggregate_matrix(matrix: Matrix, config: Config) -> Vec<U256> {
- matrix
- .iter()
- .enumerate()
- .map(|(index, values)| {
- config
- .validate_signer_count_threshold(index, values)
- .median()
- })
- .collect()
-}
-
-fn make_value_signer_matrix(config: &Config, data_packages: Vec<DataPackage>) -> Matrix {
- let mut matrix = vec![vec![None; config.signers.len()]; config.feed_ids.len()];
-
- data_packages.iter().for_each(|data_package| {
- if let Some(signer_index) = config.signer_index(&data_package.signer_address) {
- data_package.data_points.iter().for_each(|data_point| {
- if let Some(feed_index) = config.feed_index(data_point.feed_id) {
- matrix[feed_index][signer_index] = data_point.value.into()
- }
- })
- }
- });
-
- print_debug!("{:?}", matrix);
-
- matrix
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod aggregate_matrix_tests {
- use crate::{
- core::{aggregator::aggregate_matrix, config::Config},
- helpers::iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- };
-
- #[test]
- fn test_aggregate_matrix() {
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8, 23].iter_into_opt(),
- ];
-
- for signer_count_threshold in 0..Config::test().signers.len() + 1 {
- let mut config = Config::test();
- config.signer_count_threshold = signer_count_threshold as u8;
-
- let result = aggregate_matrix(matrix.clone(), config);
-
- assert_eq!(result, vec![12u8, 22].iter_into());
- }
- }
-
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_one_value() {
- let mut config = Config::test();
- config.signer_count_threshold = 1;
-
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8.into(), None].opt_iter_into_opt(),
- ];
-
- let result = aggregate_matrix(matrix, config);
-
- assert_eq!(result, vec![12u8, 21].iter_into());
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_whole_feed() {
- let mut config = Config::test();
- config.signer_count_threshold = 0;
-
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, config);
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #0 (ETH)")]
- #[test]
- fn test_aggregate_matrix_missing_one_value() {
- let matrix = vec![
- vec![21u8.into(), None].opt_iter_into_opt(),
- vec![11u8, 12].iter_into_opt(),
- ];
-
- aggregate_matrix(matrix, Config::test());
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #1 (BTC)")]
- #[test]
- fn test_aggregate_matrix_missing_whole_feed() {
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, Config::test());
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod make_value_signer_matrix {
- use crate::{
- core::{
- aggregator::{make_value_signer_matrix, Matrix},
- config::Config,
- test_helpers::{AVAX, BTC, ETH, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2},
- },
- helpers::iter_into::IterInto,
- network::specific::U256,
- protocol::data_package::DataPackage,
- };
-
- #[test]
- fn test_make_value_signer_matrix_empty() {
- let config = Config::test();
-
- test_make_value_signer_matrix_of(
- vec![],
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_exact() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_greater() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_smaller() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_diagonal() {
- let data_packages = vec![
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11.into(), None], vec![None, 22.into()]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_repetitions() {
- let data_packages = vec![
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 202, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 101, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![101, 12].iter_into(), vec![21, 202].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_all_wrong() {
- let config = Config::test();
-
- let data_packages = vec![
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_mix() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- fn test_make_value_signer_matrix_of(
- data_packages: Vec<DataPackage>,
- expected_values: Vec<Vec<Option<u128>>>,
- ) {
- let config = &Config::test();
- let result = make_value_signer_matrix(config, data_packages);
-
- let expected_matrix: Matrix = expected_values
- .iter()
- .map(|row| {
- (row.iter()
- .map(|&value| value.map(U256::from))
- .collect::<Vec<_>>())
- .iter_into() as Vec<Option<U256>>
- })
- .collect();
-
- assert_eq!(result, expected_matrix)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -
use crate::network::specific::{Bytes, U256};
-
-/// Configuration for a RedStone payload processor.
-///
-/// Specifies the parameters necessary for the verification and aggregation of values
-/// from various data points passed by the RedStone payload.
-#[derive(Debug)]
-pub struct Config {
- /// The minimum number of signers required validating the data.
- ///
- /// Specifies how many unique signers (from different addresses) are required
- /// for the data to be considered valid and trustworthy.
- pub signer_count_threshold: u8,
-
- /// List of identifiers for signers authorized to sign the data.
- ///
- /// Each signer is identified by a unique, network-specific byte string (`Bytes`),
- /// which represents their address.
- pub signers: Vec<Bytes>,
-
- /// Identifiers for the data feeds from which values are aggregated.
- ///
- /// Each data feed id is represented by the network-specific `U256` type.
- pub feed_ids: Vec<U256>,
-
- /// The current block time in timestamp format, used for verifying data timeliness.
- ///
- /// The value's been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows
- /// for determining whether the data is current in the context of blockchain time.
- pub block_timestamp: u64,
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -
use crate::{
- core::{
- aggregator::aggregate_values, config::Config, processor_result::ProcessorResult,
- validator::Validator,
- },
- network::specific::Bytes,
- print_debug,
- protocol::payload::Payload,
-};
-
-/// The main processor of the RedStone payload.
-///
-///
-/// # Arguments
-///
-/// * `config` - Configuration of the payload processing.
-/// * `payload_bytes` - Network-specific byte-list of the payload to be processed.
-pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult {
- #[allow(clippy::useless_conversion)]
- let mut bytes: Vec<u8> = payload_bytes.into();
- let payload = Payload::make(&mut bytes);
- print_debug!("{:?}", payload);
-
- make_processor_result(config, payload)
-}
-
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult {
- let min_timestamp = payload
- .data_packages
- .iter()
- .enumerate()
- .map(|(index, dp)| config.validate_timestamp(index, dp.timestamp))
- .min()
- .unwrap();
-
- let values = aggregate_values(config, payload.data_packages);
-
- print_debug!("{} {:?}", min_timestamp, values);
-
- ProcessorResult {
- values,
- min_timestamp,
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- processor::make_processor_result,
- processor_result::ProcessorResult,
- test_helpers::{
- BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- },
- helpers::iter_into::IterInto,
- protocol::{data_package::DataPackage, payload::Payload},
- };
-
- #[test]
- fn test_make_processor_result() {
- let data_packages = vec![
- DataPackage::test(
- ETH,
- 11,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 5).into(),
- ),
- DataPackage::test(
- ETH,
- 13,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP + 3).into(),
- ),
- DataPackage::test(
- BTC,
- 32,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP - 2).into(),
- ),
- DataPackage::test(
- BTC,
- 31,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 400).into(),
- ),
- ];
-
- let result = make_processor_result(Config::test(), Payload { data_packages });
-
- assert_eq!(
- result,
- ProcessorResult {
- min_timestamp: TEST_BLOCK_TIMESTAMP - 2,
- values: vec![12u8, 31].iter_into()
- }
- );
- }
-}
-
use crate::network::specific::U256;
-
-/// Represents the result of processing the RedStone payload.
-///
-/// This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-/// particularly focusing on time-sensitive data and its associated values, according to the `Config`.
-#[derive(Debug, Eq, PartialEq)]
-pub struct ProcessorResult {
- /// The minimum timestamp encountered during processing.
- ///
- /// This field captures the earliest time point (in milliseconds since the Unix epoch)
- /// among the processed data packages, indicating the starting boundary of the dataset's time range.
- pub min_timestamp: u64,
-
- /// A collection of values processed during the operation.
- ///
- /// Each element in this vector represents a processed value corresponding
- /// to the passed data_feed item in the `Config`.
- pub values: Vec<U256>,
-}
-
-impl From<ProcessorResult> for (u64, Vec<U256>) {
- fn from(result: ProcessorResult) -> Self {
- (result.min_timestamp, result.values)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -
use crate::{
- core::config::Config,
- network::{
- assert::Assert,
- error::Error::{InsufficientSignerCount, TimestampTooFuture, TimestampTooOld},
- specific::U256,
- },
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- utils::filter::FilterSome,
-};
-
-/// A trait defining validation operations for data feeds and signers.
-///
-/// This trait specifies methods for validating aspects of data feeds and signers within a system that
-/// requires data integrity and authenticity checks. Implementations of this trait are responsible for
-/// defining the logic behind each validation step, ensuring that data conforms to expected rules and
-/// conditions.
-pub(crate) trait Validator {
- /// Retrieves the index of a given data feed.
- ///
- /// This method takes a `feed_id` representing the unique identifier of a data feed and
- /// returns an `Option<usize>` indicating the index of the feed within a collection of feeds.
- /// If the feed does not exist, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `feed_id`: `U256` - The unique identifier of the data feed.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the feed if it exists, or `None` if it does not.
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
-
- /// Retrieves the index of a given signer.
- ///
- /// This method accepts a signer identifier in the form of a byte slice and returns an
- /// `Option<usize>` indicating the signer's index within a collection of signers. If the signer
- /// is not found, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `signer`: `&[u8]` - A byte slice representing the signer's identifier.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the signer if found, or `None` if not found.
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
-
- /// Validates the signer count threshold for a given index within a set of values.
- ///
- /// This method is responsible for ensuring that the number of valid signers meets or exceeds
- /// a specified threshold necessary for a set of data values to be considered valid. It returns
- /// a vector of `U256` if the values pass the validation, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value being validated.
- /// * `values`: `&[Option<U256>]` - A slice of optional `U256` values associated with the data.
- ///
- /// # Returns
- ///
- /// * `Vec<U256>` - A vector of `U256` values that meet the validation criteria.
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256>;
-
- /// Validates the timestamp for a given index.
- ///
- /// This method checks whether a timestamp associated with a data value at a given index
- /// meets specific conditions (e.g., being within an acceptable time range). It returns
- /// the validated timestamp if it's valid, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value whose timestamp is being validated.
- /// * `timestamp`: `u64` - The timestamp to be validated.
- ///
- /// # Returns
- ///
- /// * `u64` - The validated timestamp.
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
-
-impl Validator for Config {
- #[inline]
- fn feed_index(&self, feed_id: U256) -> Option<usize> {
- self.feed_ids.iter().position(|&elt| elt == feed_id)
- }
-
- #[inline]
- fn signer_index(&self, signer: &[u8]) -> Option<usize> {
- self.signers
- .iter()
- .position(|elt| elt.to_ascii_lowercase() == signer.to_ascii_lowercase())
- }
-
- #[inline]
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256> {
- values.filter_some().assert_or_revert(
- |x| (*x).len() >= self.signer_count_threshold.into(),
- #[allow(clippy::useless_conversion)]
- |val| InsufficientSignerCount(index, val.len(), self.feed_ids[index]),
- )
- }
-
- #[inline]
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64 {
- timestamp.assert_or_revert(
- |&x| x + MAX_TIMESTAMP_DELAY_MS >= self.block_timestamp,
- |timestamp| TimestampTooOld(index, *timestamp),
- );
-
- timestamp.assert_or_revert(
- |&x| x <= self.block_timestamp + MAX_TIMESTAMP_AHEAD_MS,
- |timestamp| TimestampTooFuture(index, *timestamp),
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- test_helpers::{
- AVAX, BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- validator::Validator,
- },
- helpers::{
- hex::{hex_to_bytes, make_feed_id},
- iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- },
- network::specific::U256,
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- };
- use itertools::Itertools;
-
- #[test]
- fn test_feed_index() {
- let config = Config::test();
-
- let eth_index = config.feed_index(make_feed_id(ETH));
- assert_eq!(eth_index, 0.into());
-
- let eth_index = config.feed_index(make_feed_id("778680")); //eth
- assert_eq!(eth_index, None);
-
- let btc_index = config.feed_index(make_feed_id(BTC));
- assert_eq!(btc_index, 1.into());
-
- let avax_index = config.feed_index(make_feed_id(AVAX));
- assert_eq!(avax_index, None);
- }
-
- #[test]
- fn test_signer_index() {
- let config = Config::test();
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.into()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.to_uppercase()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.into()));
- assert_eq!(index, 1.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.replace('0', "1")));
- assert_eq!(index, None);
- }
-
- #[test]
- fn test_validate_timestamp() {
- let config = Config::test();
-
- config.validate_timestamp(0, TEST_BLOCK_TIMESTAMP);
- config.validate_timestamp(1, TEST_BLOCK_TIMESTAMP + 60000);
- config.validate_timestamp(2, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS);
- config.validate_timestamp(3, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS);
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP - 60000);
- }
-
- #[should_panic(expected = "Timestamp 2000000180001 is too future for #0")]
- #[test]
- fn test_validate_timestamp_too_future() {
- Config::test().validate_timestamp(0, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS + 1);
- }
-
- #[should_panic(expected = "Timestamp 1999999099999 is too old for #1")]
- #[test]
- fn test_validate_timestamp_too_old() {
- Config::test().validate_timestamp(1, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS - 1);
- }
-
- #[should_panic(expected = "Timestamp 0 is too old for #2")]
- #[test]
- fn test_validate_timestamp_zero() {
- Config::test().validate_timestamp(2, 0);
- }
-
- #[should_panic(expected = "Timestamp 4000000000000 is too future for #3")]
- #[test]
- fn test_validate_timestamp_big() {
- Config::test().validate_timestamp(3, TEST_BLOCK_TIMESTAMP + TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Timestamp 2000000000000 is too future for #4")]
- #[test]
- fn test_validate_timestamp_no_block_timestamp() {
- let mut config = Config::test();
-
- config.block_timestamp = 0;
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #0 (ETH)")]
- #[test]
- fn test_validate_signer_count_threshold_empty_list() {
- Config::test().validate_signer_count_threshold(0, vec![].as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_shorter_list() {
- Config::test().validate_signer_count_threshold(1, vec![1u8].iter_into_opt().as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_list_with_nones() {
- Config::test().validate_signer_count_threshold(
- 1,
- vec![None, 1u8.into(), None].opt_iter_into_opt().as_slice(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_size() {
- validate_with_all_permutations(vec![1u8, 2].iter_into_opt(), vec![1u8, 2].iter_into());
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_signer_count() {
- validate_with_all_permutations(
- vec![None, 1u8.into(), None, 2.into()].opt_iter_into_opt(),
- vec![1u8, 2].iter_into(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_larger_size() {
- validate_with_all_permutations(
- vec![
- 1u8.into(),
- None,
- None,
- 2.into(),
- 3.into(),
- None,
- 4.into(),
- None,
- ]
- .opt_iter_into_opt(),
- vec![1u8, 2, 3, 4].iter_into(),
- );
- }
-
- fn validate_with_all_permutations(numbers: Vec<Option<U256>>, expected_value: Vec<U256>) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
- let mut config = Config::test();
-
- let result = config.validate_signer_count_threshold(0, &numbers);
- assert_eq!(result, expected_value);
-
- for threshold in 0..expected_value.len() + 1 {
- config.signer_count_threshold = threshold as u8;
-
- for (index, perm) in perms.iter().enumerate() {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- let result =
- config.validate_signer_count_threshold(index % config.feed_ids.len(), &p);
- assert_eq!(result.len(), expected_value.len());
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -
use sha3::{Digest, Keccak256};
-
-pub fn keccak256(data: &[u8]) -> Box<[u8]> {
- Keccak256::new_with_prefix(data)
- .finalize()
- .as_slice()
- .into()
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{crypto::keccak256::keccak256, helpers::hex::hex_to_bytes};
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const EMPTY_MESSAGE_HASH: &str =
- "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
-
- #[test]
- fn test_keccak256() {
- let hash = keccak256(hex_to_bytes(MESSAGE.into()).as_slice());
-
- assert_eq!(hash.as_ref(), hex_to_bytes(MESSAGE_HASH.into()).as_slice());
- }
-
- #[test]
- fn test_keccak256_empty() {
- let hash = keccak256(vec![].as_slice());
-
- assert_eq!(
- hash.as_ref(),
- hex_to_bytes(EMPTY_MESSAGE_HASH.into()).as_slice()
- );
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -
use crate::crypto::{keccak256, recover::crypto256::recover_public_key};
-
-pub fn recover_address(message: Vec<u8>, signature: Vec<u8>) -> Vec<u8> {
- let recovery_byte = signature[64]; // 65-byte representation
- let msg_hash = keccak256::keccak256(message.as_slice());
- let key = recover_public_key(
- msg_hash,
- &signature[..64],
- recovery_byte - (if recovery_byte >= 27 { 27 } else { 0 }),
- );
- let key_hash = keccak256::keccak256(&key[1..]); // skip first uncompressed-key byte
-
- key_hash[12..].into() // last 20 bytes
-}
-
-#[cfg(feature = "crypto_secp256k1")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use secp256k1::{ecdsa::RecoverableSignature, Message, Secp256k1 as Secp256k1Curve};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let msg = Message::from_digest_slice(message_hash.as_ref())
- .unwrap_or_revert(|_| Error::CryptographicError(message_hash.len()));
-
- let recovery_id = secp256k1::ecdsa::RecoveryId::from_i32(recovery_byte.into())
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let sig: RecoverableSignature =
- RecoverableSignature::from_compact(signature_bytes, recovery_id)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let public_key = Secp256k1Curve::new().recover_ecdsa(&msg, &sig);
-
- public_key.unwrap().serialize_uncompressed().into()
- }
-}
-
-#[cfg(feature = "crypto_k256")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let recovery_id = RecoveryId::from_byte(recovery_byte)
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let signature = Signature::try_from(signature_bytes)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let recovered_key =
- VerifyingKey::recover_from_prehash(message_hash.as_ref(), &signature, recovery_id)
- .map(|key| key.to_encoded_point(false).to_bytes());
-
- recovered_key.unwrap()
- }
-}
-
-#[cfg(all(not(feature = "crypto_k256"), not(feature = "crypto_secp256k1")))]
-pub(crate) mod crypto256 {
- pub(crate) fn recover_public_key(
- _message_hash: Box<[u8]>,
- _signature_bytes: &[u8],
- _recovery_byte: u8,
- ) -> Box<[u8]> {
- panic!("Not implemented!")
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- crypto::recover::{crypto256::recover_public_key, recover_address},
- helpers::hex::hex_to_bytes,
- };
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const SIG_V27: &str = "475195641dae43318e194c3d9e5fc308773d6fdf5e197e02644dfd9ca3d19e3e2bd7d8656428f7f02e658a16b8f83722169c57126cc50bec8fad188b1bac6d19";
- const SIG_V28: &str = "c88242d22d88252c845b946c9957dbf3c7d59a3b69ecba2898198869f9f146ff268c3e47a11dbb05cc5198aadd659881817a59ee37e088d3253f4695927428c1";
- const PUBLIC_KEY_V27: &str =
- "04f5f035588502146774d0ccfd62ee5bf1d7f1dbb96aae33a79765c636b8ec75a36f5121931b5cc37215a7d4280c5700ca92daaaf93c32b06ca9f98b1f4ece624e";
- const PUBLIC_KEY_V28: &str =
- "04626f2ad2cfb0b41a24276d78de8959bcf45fc5e80804416e660aab2089d15e98206526e639ee19d17c8f9ae0ce3a6ff1a8ea4ab773d0fb4214e08aad7ba978c8";
- const ADDRESS_V27: &str = "2c59617248994D12816EE1Fa77CE0a64eEB456BF";
- const ADDRESS_V28: &str = "12470f7aBA85c8b81D63137DD5925D6EE114952b";
-
- #[test]
- fn test_recover_public_key_v27() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V27), 0);
-
- assert_eq!(u8_box(PUBLIC_KEY_V27), public_key);
- }
-
- #[test]
- fn test_recover_public_key_v28() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V28), 1);
-
- assert_eq!(u8_box(PUBLIC_KEY_V28), public_key);
- }
-
- #[test]
- fn test_recover_address_1b() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V27.to_owned() + "1b"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V27.into()), address);
- }
-
- #[test]
- fn test_recover_address_1c() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V28.to_owned() + "1c"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V28.into()), address);
- }
-
- fn u8_box(str: &str) -> Box<[u8]> {
- hex_to_bytes(str.into()).as_slice().into()
- }
-}
-
//! # RedStone
-//!
-//! `redstone` is a collection of utilities to make deserializing&decrypting RedStone payload.
-//! It contains a pure Rust implementation and also an extension for some networks.
-//!
-//! Different crypto-mechanisms are easily injectable.
-//! The current implementation contains `secp256k1`- and `k256`-based variants.
-
-pub mod core;
-mod crypto;
-pub mod network;
-mod protocol;
-mod utils;
-
-#[cfg(feature = "helpers")]
-pub mod helpers;
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -
extern crate alloc;
-
-use crate::network::specific::U256;
-use alloc::{format, string::String};
-
-pub trait AsHexStr {
- fn as_hex_str(&self) -> String;
-}
-
-impl AsHexStr for &[u8] {
- #[allow(clippy::format_collect)]
- fn as_hex_str(&self) -> String {
- self.iter().map(|byte| format!("{:02x}", byte)).collect()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsHexStr for casper_types::bytesrepr::Bytes {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- format!("{:X}", self)
- }
-}
-
-#[cfg(feature = "network_radix")]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- let digits = self.to_digits();
- let mut result = String::new();
- for &part in &digits {
- if result.is_empty() || part != 0u64 {
- result.push_str(&format!("{:02X}", part));
- }
- }
- result
- }
-}
-
-impl AsHexStr for Vec<u8> {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-impl AsHexStr for Box<[u8]> {
- fn as_hex_str(&self) -> String {
- self.as_ref().as_hex_str()
- }
-}
-
-pub trait AsAsciiStr {
- fn as_ascii_str(&self) -> String;
-}
-
-impl AsAsciiStr for &[u8] {
- fn as_ascii_str(&self) -> String {
- self.iter().map(|&code| code as char).collect()
- }
-}
-
-impl AsAsciiStr for Vec<u8> {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsAsciiStr for casper_types::bytesrepr::Bytes {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-impl AsAsciiStr for U256 {
- fn as_ascii_str(&self) -> String {
- let hex_string = self.as_hex_str();
- let bytes = (0..hex_string.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&hex_string[i..i + 2], 16))
- .collect::<Result<Vec<u8>, _>>()
- .unwrap();
-
- bytes.as_ascii_str()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
- };
-
- const ETH: u32 = 4543560u32;
-
- #[test]
- fn test_as_hex_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_hex_str();
-
- assert_eq!(result, "455448");
- }
-
- #[test]
- fn test_as_ascii_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_ascii_str();
-
- assert_eq!(result, "ETH");
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -
use crate::{
- network::{error::Error, specific::revert},
- print_debug,
-};
-use std::fmt::Debug;
-
-pub trait Assert<F> {
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
-
-impl<T, F> Assert<F> for T
-where
- T: Debug,
- F: Fn(&Self) -> bool,
-{
- fn assert_or_revert<E: FnOnce(&Self) -> Error>(self, check: F, error: E) -> Self {
- assert_or_revert(self, check, error)
- }
-}
-
-#[inline]
-fn assert_or_revert<F, T, E: FnOnce(&T) -> Error>(arg: T, check: F, error: E) -> T
-where
- F: Fn(&T) -> bool,
- T: Debug,
-{
- assert_or_revert_bool_with(check(&arg), || error(&arg));
-
- arg
-}
-
-#[inline]
-fn assert_or_revert_bool_with<E: FnOnce() -> Error>(check: bool, error: E) {
- if check {
- return;
- }
-
- let error = error();
- print_debug!("REVERT({}) - {}!", &error.code(), error);
- revert(error);
-}
-
-pub trait Unwrap<R> {
- type ErrorArg;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
-
-impl<T> Unwrap<T> for Option<T>
-where
- T: Debug,
-{
- type ErrorArg = ();
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(self, |arg| arg.is_some(), |_| error(&())).unwrap()
- }
-}
-
-impl<T, Err> Unwrap<T> for Result<T, Err>
-where
- T: Debug,
- Err: Debug,
-{
- type ErrorArg = Err;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(
- self,
- |arg| arg.is_ok(),
- |e| error(e.as_ref().err().unwrap()),
- )
- .unwrap()
- }
-}
-
-#[cfg(test)]
-mod assert_or_revert_tests {
- use crate::network::{
- assert::{assert_or_revert_bool_with, Assert},
- error::Error,
- };
-
- #[test]
- fn test_assert_or_revert_bool_with_true() {
- assert_or_revert_bool_with(true, || Error::ArrayIsEmpty);
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_assert_or_revert_bool_with_false() {
- assert_or_revert_bool_with(false, || Error::ArrayIsEmpty);
- }
-
- #[test]
- fn test_assert_or_revert_correct() {
- 5.assert_or_revert(|&x| x == 5, |&size| Error::SizeNotSupported(size));
- }
-
- #[should_panic(expected = "Size not supported: 5")]
- #[test]
- fn test_assert_or_revert_wrong() {
- 5.assert_or_revert(|&x| x < 5, |&size| Error::SizeNotSupported(size));
- }
-}
-
-#[cfg(test)]
-mod unwrap_or_revert_tests {
- use crate::network::{assert::Unwrap, error::Error};
-
- #[test]
- fn test_unwrap_or_revert_some() {
- let result = Some(543).unwrap_or_revert(|_| Error::CryptographicError(333));
-
- assert_eq!(result, 543);
- }
-
- #[should_panic(expected = "Cryptographic Error: 333")]
- #[test]
- fn test_unwrap_or_revert_none() {
- (Option::<u64>::None).unwrap_or_revert(|_| Error::CryptographicError(333));
- }
-
- #[test]
- fn test_unwrap_or_revert_ok() {
- let result = Ok(256).unwrap_or_revert(|_: &Error| Error::CryptographicError(333));
-
- assert_eq!(result, 256);
- }
-
- #[should_panic(expected = "Cryptographic Error: 567")]
- #[test]
- fn test_unwrap_or_revert_err() {
- Result::<&[u8], Error>::Err(Error::CryptographicError(567)).unwrap_or_revert(|e| e.clone());
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod error;
-mod from_bytes_repr;
-
-pub struct Casper;
-
-impl NetworkSpecific for Casper {
- type BytesRepr = casper_types::bytesrepr::Bytes;
- type ValueRepr = casper_types::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- casper_contract::contract_api::runtime::print(&_text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- casper_contract::contract_api::runtime::revert(error)
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -
use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
-};
-use std::fmt::{Debug, Display, Formatter};
-
-pub trait ContractErrorContent: Debug {
- fn code(&self) -> u8;
- fn message(&self) -> String;
-}
-
-/// Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-///
-/// These errors include issues with contract logic, data types,
-/// cryptographic operations, and conditions specific to the requirements.
-#[derive(Debug)]
-pub enum Error {
- /// Represents errors that arise from the contract itself.
- ///
- /// This variant is used for encapsulating errors that are specific to the contract's logic
- /// or execution conditions that aren't covered by more specific error types.
- ContractError(Box<dyn ContractErrorContent>),
-
- /// Indicates an overflow error with `U256` numbers.
- ///
- /// Used when operations on `U256` numbers exceed their maximum value, potentially leading
- /// to incorrect calculations or state.
- NumberOverflow(U256),
-
- /// Used when an expected non-empty array or vector is found to be empty.
- ///
- /// This could occur in scenarios where the contract logic requires a non-empty collection
- /// of items for the correct operation, for example, during aggregating the values.
- ArrayIsEmpty,
-
- /// Represents errors related to cryptographic operations.
- ///
- /// This includes failures in signature verification, hashing, or other cryptographic
- /// processes, with the usize indicating the position or identifier of the failed operation.
- CryptographicError(usize),
-
- /// Signifies that an unsupported size was encountered.
- ///
- /// This could be used when a data structure or input does not meet the expected size
- /// requirements for processing.
- SizeNotSupported(usize),
-
- /// Indicates that the marker bytes for RedStone are incorrect.
- ///
- /// This error is specific to scenarios where marker or identifier bytes do not match
- /// expected values, potentially indicating corrupted or tampered data.
- WrongRedStoneMarker(Vec<u8>),
-
- /// Used when there is leftover data in a payload that should have been empty.
- ///
- /// This could indicate an error in data parsing or that additional, unexpected data
- /// was included in a message or transaction.
- NonEmptyPayloadRemainder(Vec<u8>),
-
- /// Indicates that the number of signers does not meet the required threshold.
- ///
- /// This variant includes the current number of signers, the required threshold, and
- /// potentially a feed_id related to the operation that failed due to insufficient signers.
- InsufficientSignerCount(usize, usize, U256),
-
- /// Used when a timestamp is older than allowed by the processor logic.
- ///
- /// Includes the position or identifier of the timestamp and the threshold value,
- /// indicating that the provided timestamp is too far in the past.
- TimestampTooOld(usize, u64),
-
- /// Indicates that a timestamp is further in the future than allowed.
- ///
- /// Similar to `TimestampTooOld`, but for future timestamps exceeding the contract's
- /// acceptance window.
- TimestampTooFuture(usize, u64),
-
- /// Represents errors that need to clone `ContractErrorContent`, which is not supported by default.
- ///
- /// This variant allows for the manual duplication of contract error information, including
- /// an error code and a descriptive message.
- ClonedContractError(u8, String),
-}
-
-impl Error {
- pub fn contract_error<T: ContractErrorContent + 'static>(value: T) -> Error {
- Error::ContractError(Box::new(value))
- }
-
- pub(crate) fn code(&self) -> u16 {
- match self {
- Error::ContractError(boxed) => boxed.code() as u16,
- Error::NumberOverflow(_) => 509,
- Error::ArrayIsEmpty => 510,
- Error::WrongRedStoneMarker(_) => 511,
- Error::NonEmptyPayloadRemainder(_) => 512,
- Error::InsufficientSignerCount(data_package_index, value, _) => {
- (2000 + data_package_index * 10 + value) as u16
- }
- Error::SizeNotSupported(size) => 600 + *size as u16,
- Error::CryptographicError(size) => 700 + *size as u16,
- Error::TimestampTooOld(data_package_index, _) => 1000 + *data_package_index as u16,
- Error::TimestampTooFuture(data_package_index, _) => 1050 + *data_package_index as u16,
- Error::ClonedContractError(code, _) => *code as u16,
- }
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- Error::ContractError(boxed) => write!(f, "Contract error: {}", boxed.message()),
- Error::NumberOverflow(number) => write!(f, "Number overflow: {}", number),
- Error::ArrayIsEmpty => write!(f, "Array is empty"),
- Error::CryptographicError(size) => write!(f, "Cryptographic Error: {}", size),
- Error::SizeNotSupported(size) => write!(f, "Size not supported: {}", size),
- Error::WrongRedStoneMarker(bytes) => {
- write!(f, "Wrong RedStone marker: {}", bytes.as_hex_str())
- }
- Error::NonEmptyPayloadRemainder(bytes) => {
- write!(f, "Non empty payload remainder: {}", bytes.as_hex_str())
- }
- Error::InsufficientSignerCount(data_package_index, value, feed_id) => write!(
- f,
- "Insufficient signer count {} for #{} ({})",
- value,
- data_package_index,
- feed_id.as_ascii_str()
- ),
- Error::TimestampTooOld(data_package_index, value) => {
- write!(
- f,
- "Timestamp {} is too old for #{}",
- value, data_package_index
- )
- }
- Error::TimestampTooFuture(data_package_index, value) => write!(
- f,
- "Timestamp {} is too future for #{}",
- value, data_package_index
- ),
- Error::ClonedContractError(_, message) => {
- write!(f, "(Cloned) Contract error: {}", message)
- }
- }
- }
-}
-
-impl Clone for Error {
- fn clone(&self) -> Self {
- match self {
- Error::ContractError(content) => {
- Error::ClonedContractError(content.code(), content.message())
- }
- Error::NumberOverflow(value) => Error::NumberOverflow(*value),
- Error::ArrayIsEmpty => Error::ArrayIsEmpty,
- Error::CryptographicError(size) => Error::CryptographicError(*size),
- Error::SizeNotSupported(size) => Error::SizeNotSupported(*size),
- Error::WrongRedStoneMarker(bytes) => Error::WrongRedStoneMarker(bytes.clone()),
- Error::NonEmptyPayloadRemainder(bytes) => {
- Error::NonEmptyPayloadRemainder(bytes.clone())
- }
- Error::InsufficientSignerCount(count, needed, bytes) => {
- Error::InsufficientSignerCount(*count, *needed, *bytes)
- }
- Error::TimestampTooOld(index, timestamp) => Error::TimestampTooOld(*index, *timestamp),
- Error::TimestampTooFuture(index, timestamp) => {
- Error::TimestampTooFuture(*index, *timestamp)
- }
- Error::ClonedContractError(code, message) => {
- Error::ClonedContractError(*code, message.as_str().into())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -
use crate::network::specific::Bytes;
-
-pub trait Flattened<T> {
- fn flattened(&self) -> T;
-}
-
-impl Flattened<Bytes> for Vec<Bytes> {
- fn flattened(&self) -> Bytes {
- #[allow(clippy::useless_conversion)]
- self.iter().flatten().copied().collect::<Vec<_>>().into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{flattened::Flattened, specific::Bytes};
-
- #[test]
- fn test_bytes_flattened() {
- #[allow(clippy::useless_conversion)]
- let bytes: Vec<Bytes> = vec![
- vec![1u8, 2, 3].into(),
- vec![4u8].into(),
- vec![].into(),
- vec![5, 6, 7].into(),
- ];
-
- let result: Bytes = bytes.flattened();
-
- #[allow(clippy::useless_conversion)]
- let expected_result: Bytes = vec![1u8, 2, 3, 4, 5, 6, 7].into();
-
- assert_eq!(result, expected_result);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -
use crate::network::specific::VALUE_SIZE;
-
-pub trait FromBytesRepr<T> {
- fn from_bytes_repr(bytes: T) -> Self;
-}
-
-pub trait Sanitized {
- fn sanitized(self) -> Self;
-}
-
-impl Sanitized for Vec<u8> {
- fn sanitized(self) -> Self {
- if self.len() <= VALUE_SIZE {
- return self;
- }
-
- let index = self.len().max(VALUE_SIZE) - VALUE_SIZE;
- let remainder = &self[0..index];
-
- if remainder != vec![0; index] {
- panic!("Number to big: {:?} digits", self.len())
- }
-
- self[index..].into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- };
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[test]
- fn test_from_bytes_repr_single() {
- let vec = vec![1];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(1u32));
- }
-
- #[test]
- fn test_from_bytes_repr_double() {
- let vec = vec![1, 2];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(258u32));
- }
-
- #[test]
- fn test_from_bytes_repr_simple() {
- let vec = vec![1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[test]
- fn test_from_bytes_repr_bigger() {
- let vec = vec![101, 202, 255];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(6671103u32));
- }
-
- #[test]
- fn test_from_bytes_repr_empty() {
- let result = U256::from_bytes_repr(Vec::new());
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[test]
- fn test_from_bytes_repr_trailing_zeroes() {
- let vec = vec![1, 2, 3, 0];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(16909056u32));
- }
-
- #[test]
- fn test_from_bytes_repr_leading_zeroes() {
- let vec = vec![0, 1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_max() {
- let vec = vec![255; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-
- #[test]
- fn test_from_bytes_repr_min() {
- let vec = vec![0; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[should_panic(expected = "Number to big")]
- #[test]
- fn test_from_bytes_repr_too_long() {
- let x = VALUE_SIZE as u8 + 1;
- let vec = (1..=x).collect();
-
- U256::from_bytes_repr(vec);
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_too_long_but_zeroes() {
- let mut vec = vec![255; VALUE_SIZE + 1];
- vec[0] = 0;
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-}
-
pub mod as_str;
-pub mod assert;
-pub mod error;
-pub mod from_bytes_repr;
-pub mod print_debug;
-pub mod specific;
-
-#[cfg(feature = "network_casper")]
-pub mod casper;
-
-#[cfg(feature = "network_casper")]
-pub type _Network = casper::Casper;
-
-#[cfg(feature = "network_radix")]
-pub mod radix;
-
-#[cfg(feature = "network_radix")]
-pub type _Network = radix::Radix;
-
-pub mod flattened;
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-mod pure;
-
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-pub type _Network = pure::Std;
-
extern crate alloc;
-
-#[macro_export]
-macro_rules! print_debug {
- ($fmt:expr) => {
- $crate::network::specific::print(format!($fmt))
- };
- ($fmt:expr, $($args:tt)*) => {
- $crate::network::specific::print(format!($fmt, $($args)*))
- };
-}
-
-#[macro_export]
-macro_rules! print_and_panic {
- ($fmt:expr) => {{
- $crate::print_debug!($fmt);
- panic!($fmt)
- }};
- ($fmt:expr, $($args:tt)*) => {{
- $crate::print_debug!($fmt, $($args)*);
- panic!($fmt, $($args)*)
- }};
-}
-
use crate::network::{error::Error, specific::NetworkSpecific};
-use primitive_types::U256;
-use std::eprintln;
-
-mod from_bytes_repr;
-
-pub struct Std;
-
-impl NetworkSpecific for Std {
- type BytesRepr = Vec<u8>;
- type ValueRepr = U256;
- type _Self = Std;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(text: String) {
- eprintln!("{}", text)
- }
-
- fn revert(error: Error) -> ! {
- panic!("{}", error)
- }
-}
-
use crate::network::{
- from_bytes_repr::{FromBytesRepr, Sanitized},
- specific::U256,
-};
-
-impl FromBytesRepr<Vec<u8>> for U256 {
- fn from_bytes_repr(bytes: Vec<u8>) -> Self {
- match bytes.len() {
- 0 => U256::ZERO,
- 1 => U256::from(bytes[0]),
- _ => {
- // TODO: make it cheaper
- let mut bytes_le = bytes.sanitized();
- bytes_le.reverse();
-
- U256::from_le_bytes(bytes_le.as_slice())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod from_bytes_repr;
-pub mod u256_ext;
-
-pub struct Radix;
-
-impl NetworkSpecific for Radix {
- type BytesRepr = Vec<u8>;
- type ValueRepr = radix_common::math::bnum_integer::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- scrypto::prelude::info!("{}", _text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- scrypto::prelude::Runtime::panic(error.to_string())
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
use crate::network::{_Network, error::Error, from_bytes_repr::FromBytesRepr};
-
-pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
-
-pub(crate) type Network = <_Network as NetworkSpecific>::_Self;
-pub type Bytes = <_Network as NetworkSpecific>::BytesRepr;
-pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
-pub const VALUE_SIZE: usize = <_Network as NetworkSpecific>::VALUE_SIZE;
-
-pub fn print(_text: String) {
- Network::print(_text)
-}
-
-pub fn revert(error: Error) -> ! {
- Network::revert(error)
-}
-
pub(crate) const UNSIGNED_METADATA_BYTE_SIZE_BS: usize = 3;
-pub(crate) const DATA_PACKAGES_COUNT_BS: usize = 2;
-pub(crate) const DATA_POINTS_COUNT_BS: usize = 3;
-pub(crate) const SIGNATURE_BS: usize = 65;
-pub(crate) const DATA_POINT_VALUE_BYTE_SIZE_BS: usize = 4;
-pub(crate) const DATA_FEED_ID_BS: usize = 32;
-pub(crate) const TIMESTAMP_BS: usize = 6;
-pub(crate) const MAX_TIMESTAMP_DELAY_MS: u64 = 15 * 60 * 1000; // 15 minutes in milliseconds
-pub(crate) const MAX_TIMESTAMP_AHEAD_MS: u64 = 3 * 60 * 1000; // 3 minutes in milliseconds
-pub(crate) const REDSTONE_MARKER_BS: usize = 9;
-pub(crate) const REDSTONE_MARKER: [u8; 9] = [0, 0, 2, 237, 87, 1, 30, 0, 0]; // 0x000002ed57011e0000
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -
use crate::{
- crypto::recover::recover_address,
- network::as_str::AsHexStr,
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_point::{trim_data_points, DataPoint},
- },
- utils::trim::Trim,
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
-
-pub(crate) fn trim_data_packages(payload: &mut Vec<u8>, count: usize) -> Vec<DataPackage> {
- let mut data_packages = Vec::new();
-
- for _ in 0..count {
- let data_package = trim_data_package(payload);
- data_packages.push(data_package);
- }
-
- data_packages
-}
-
-fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage {
- let signature = payload.trim_end(SIGNATURE_BS);
- let mut tmp = payload.clone();
-
- let data_point_count = payload.trim_end(DATA_POINTS_COUNT_BS);
- let value_size = payload.trim_end(DATA_POINT_VALUE_BYTE_SIZE_BS);
- let timestamp = payload.trim_end(TIMESTAMP_BS);
- let size = data_point_count * (value_size + DATA_FEED_ID_BS)
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + DATA_POINTS_COUNT_BS;
-
- let signable_bytes = tmp.trim_end(size);
- let signer_address = recover_address(signable_bytes, signature);
-
- let data_points = trim_data_points(payload, data_point_count, value_size);
-
- DataPackage {
- data_points,
- timestamp,
- signer_address,
- }
-}
-
-impl Debug for DataPackage {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPackage {{\n signer_address: 0x{}, timestamp: {},\n data_points: {:?}\n}}",
- self.signer_address.as_hex_str(),
- self.timestamp,
- self.data_points
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{from_bytes_repr::FromBytesRepr, specific::U256},
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_package::{trim_data_package, trim_data_packages, DataPackage},
- data_point::DataPoint,
- },
- };
-
- const DATA_PACKAGE_BYTES_1: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e018d79bf0ba00000002000000151afa8c5c3caf6004b42c0fb17723e524f993b9ecbad3b9bce5ec74930fa436a3660e8edef10e96ee5f222de7ef5787c02ca467c0ec18daa2907b43ac20c63c11c";
- const DATA_PACKAGE_BYTES_2: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cdd851e018d79bf0ba000000020000001473fd9dc72e6814a7de719b403cf4c9eba08934a643fd0666c433b806b31e69904f2226ffd3c8ef75861b11b5e32a1fda4b1458e0da4605a772dfba2a812f3ee1b";
-
- const SIGNER_ADDRESS_1: &str = "1ea62d73edf8ac05dfcea1a34b9796e937a29eff";
- const SIGNER_ADDRESS_2: &str = "109b4a318a4f5ddcbca6349b45f881b4137deafb";
-
- const VALUE_1: u128 = 232141080910;
- const VALUE_2: u128 = 232144078110;
-
- const DATA_PACKAGE_SIZE: usize = 32
- + DATA_FEED_ID_BS
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + SIGNATURE_BS
- + DATA_POINTS_COUNT_BS;
-
- #[test]
- fn test_trim_data_packages() {
- test_trim_data_packages_of(2, "");
- test_trim_data_packages_of(0, "");
- test_trim_data_packages_of(1, "");
- }
-
- #[test]
- fn test_trim_data_packages_with_prefix() {
- let prefix = "da4687f1914a1c";
-
- test_trim_data_packages_of(2, prefix);
- }
-
- #[test]
- fn test_trim_data_packages_single() {
- let mut bytes = hex_to_bytes(DATA_PACKAGE_BYTES_1.into());
- let data_packages = trim_data_packages(&mut bytes, 1);
- assert_eq!(data_packages.len(), 1);
- assert_eq!(bytes, Vec::<u8>::new());
-
- verify_data_package(data_packages[0].clone(), VALUE_1, SIGNER_ADDRESS_1);
- }
-
- fn test_trim_data_packages_of(count: usize, prefix: &str) {
- let input: Vec<u8> =
- hex_to_bytes((prefix.to_owned() + DATA_PACKAGE_BYTES_1) + DATA_PACKAGE_BYTES_2);
- let mut bytes = input.clone();
- let data_packages = trim_data_packages(&mut bytes, count);
-
- assert_eq!(data_packages.len(), count);
- assert_eq!(
- bytes.as_slice(),
- &input[..input.len() - count * DATA_PACKAGE_SIZE]
- );
-
- let values = &[VALUE_2, VALUE_1];
- let signers = &[SIGNER_ADDRESS_2, SIGNER_ADDRESS_1];
-
- for i in 0..count {
- verify_data_package(data_packages[i].clone(), values[i], signers[i]);
- }
- }
-
- #[should_panic(expected = "index out of bounds")]
- #[test]
- fn test_trim_data_packages_bigger_number() {
- test_trim_data_packages_of(3, "");
- }
-
- #[test]
- fn test_trim_data_package() {
- test_trim_data_package_of(DATA_PACKAGE_BYTES_1, VALUE_1, SIGNER_ADDRESS_1);
- test_trim_data_package_of(DATA_PACKAGE_BYTES_2, VALUE_2, SIGNER_ADDRESS_2);
- }
-
- #[test]
- fn test_trim_data_package_with_prefix() {
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_1),
- VALUE_1,
- SIGNER_ADDRESS_1,
- );
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_2),
- VALUE_2,
- SIGNER_ADDRESS_2,
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_signature_only() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1[(DATA_PACKAGE_BYTES_1.len() - 2 * SIGNATURE_BS)..],
- 0,
- "",
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_shorter() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1
- [(DATA_PACKAGE_BYTES_1.len() - 2 * (SIGNATURE_BS + DATA_POINTS_COUNT_BS))..],
- 0,
- "",
- );
- }
-
- fn test_trim_data_package_of(bytes_str: &str, expected_value: u128, signer_address: &str) {
- let mut bytes: Vec<u8> = hex_to_bytes(bytes_str.into());
- let result = trim_data_package(&mut bytes);
- assert_eq!(
- bytes,
- hex_to_bytes(bytes_str[..bytes_str.len() - 2 * (DATA_PACKAGE_SIZE)].into())
- );
-
- verify_data_package(result, expected_value, signer_address);
- }
-
- fn verify_data_package(result: DataPackage, expected_value: u128, signer_address: &str) {
- let data_package = DataPackage {
- data_points: vec![DataPoint {
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_PACKAGE_BYTES_1[..6].into())),
- value: U256::from(expected_value),
- }],
- timestamp: 1707144580000,
- signer_address: hex_to_bytes(signer_address.into()),
- };
-
- assert_eq!(result, data_package);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -
use crate::{
- network::{
- as_str::{AsAsciiStr, AsHexStr},
- assert::Assert,
- error::Error,
- from_bytes_repr::FromBytesRepr,
- specific::U256,
- },
- protocol::constants::DATA_FEED_ID_BS,
- utils::{trim::Trim, trim_zeros::TrimZeros},
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
-
-pub(crate) fn trim_data_points(
- payload: &mut Vec<u8>,
- count: usize,
- value_size: usize,
-) -> Vec<DataPoint> {
- count.assert_or_revert(|&count| count == 1, |&count| Error::SizeNotSupported(count));
-
- let mut data_points = Vec::new();
-
- for _ in 0..count {
- let data_point = trim_data_point(payload, value_size);
- data_points.push(data_point);
- }
-
- data_points
-}
-
-fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint {
- let value = payload.trim_end(value_size);
- let feed_id: Vec<u8> = payload.trim_end(DATA_FEED_ID_BS);
-
- DataPoint {
- value,
- feed_id: U256::from_bytes_repr(feed_id.trim_zeros()),
- }
-}
-
-impl Debug for DataPoint {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPoint {{\n feed_id: {:?} (0x{}), value: {}\n }}",
- self.feed_id.as_ascii_str(),
- self.feed_id.as_hex_str(),
- self.value,
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- },
- protocol::{
- constants::DATA_FEED_ID_BS,
- data_point::{trim_data_point, trim_data_points, DataPoint},
- },
- };
- use std::ops::Shr;
-
- const DATA_POINT_BYTES_TAIL: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e";
- const VALUE: u128 = 232141080910;
-
- #[test]
- fn test_trim_data_points() {
- let mut bytes = hex_to_bytes(DATA_POINT_BYTES_TAIL.into());
- let result = trim_data_points(&mut bytes, 1, 32);
-
- assert_eq!(result.len(), 1);
-
- verify_rest_and_result(
- DATA_POINT_BYTES_TAIL,
- 32,
- VALUE.into(),
- bytes,
- result[0].clone(),
- )
- }
-
- #[should_panic(expected = "Size not supported: 0")]
- #[test]
- fn test_trim_zero_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 0, 32);
- }
-
- #[should_panic(expected = "Size not supported: 2")]
- #[test]
- fn test_trim_two_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 2, 32);
- }
-
- #[test]
- fn test_trim_data_point() {
- test_trim_data_point_of(DATA_POINT_BYTES_TAIL, 32, VALUE.into());
- }
-
- #[test]
- fn test_trim_data_point_with_prefix() {
- test_trim_data_point_of(
- &("a2a812f3ee1b".to_owned() + DATA_POINT_BYTES_TAIL),
- 32,
- VALUE.into(),
- );
- }
-
- #[test]
- fn test_trim_data_point_other_lengths() {
- for i in 1..VALUE_SIZE {
- test_trim_data_point_of(
- &DATA_POINT_BYTES_TAIL[..DATA_POINT_BYTES_TAIL.len() - 2 * i],
- 32 - i,
- U256::from(VALUE).shr(8 * i as u32),
- );
- }
- }
-
- fn test_trim_data_point_of(value: &str, size: usize, expected_value: U256) {
- let mut bytes = hex_to_bytes(value.into());
- let result = trim_data_point(&mut bytes, size);
-
- verify_rest_and_result(value, size, expected_value, bytes, result);
- }
-
- fn verify_rest_and_result(
- value: &str,
- size: usize,
- expected_value: U256,
- rest: Vec<u8>,
- result: DataPoint,
- ) {
- assert_eq!(
- rest,
- hex_to_bytes(value[..value.len() - 2 * (size + DATA_FEED_ID_BS)].into())
- );
-
- let data_point = DataPoint {
- value: expected_value,
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_POINT_BYTES_TAIL[..6].to_string())),
- };
-
- assert_eq!(result, data_point);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
-};
-
-pub fn trim_redstone_marker(payload: &mut Vec<u8>) {
- let marker: Vec<u8> = payload.trim_end(REDSTONE_MARKER_BS);
-
- marker.as_slice().assert_or_revert(
- |&marker| marker == REDSTONE_MARKER,
- |&val| Error::WrongRedStoneMarker(val.into()),
- );
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- protocol::{constants::REDSTONE_MARKER_BS, marker::trim_redstone_marker},
- };
-
- const PAYLOAD_TAIL: &str = "1c000f000000000002ed57011e0000";
-
- #[test]
- fn test_trim_redstone_marker() {
- let mut bytes = hex_to_bytes(PAYLOAD_TAIL.into());
- trim_redstone_marker(&mut bytes);
-
- assert_eq!(
- bytes,
- hex_to_bytes(PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2 * REDSTONE_MARKER_BS].into())
- );
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 000002ed57022e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong() {
- trim_redstone_marker(&mut hex_to_bytes(PAYLOAD_TAIL.replace('1', "2")));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 00000002ed57011e00")]
- #[test]
- fn test_trim_redstone_marker_wrong_ending() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2].into(),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 100002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong_beginning() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL.replace("0000000", "1111111"),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 0002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_too_short() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[PAYLOAD_TAIL.len() - 2 * (REDSTONE_MARKER_BS - 1)..].into(),
- ));
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::{
- constants::{DATA_PACKAGES_COUNT_BS, UNSIGNED_METADATA_BYTE_SIZE_BS},
- data_package::{trim_data_packages, DataPackage},
- marker,
- },
- utils::trim::Trim,
-};
-
-#[derive(Clone, Debug)]
-pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
-
-impl Payload {
- pub(crate) fn make(payload_bytes: &mut Vec<u8>) -> Payload {
- marker::trim_redstone_marker(payload_bytes);
- let payload = trim_payload(payload_bytes);
-
- payload_bytes.assert_or_revert(
- |bytes| bytes.is_empty(),
- |bytes| Error::NonEmptyPayloadRemainder(bytes.as_slice().into()),
- );
-
- payload
- }
-}
-
-fn trim_payload(payload: &mut Vec<u8>) -> Payload {
- let data_package_count = trim_metadata(payload);
- let data_packages = trim_data_packages(payload, data_package_count);
-
- Payload { data_packages }
-}
-
-fn trim_metadata(payload: &mut Vec<u8>) -> usize {
- let unsigned_metadata_size = payload.trim_end(UNSIGNED_METADATA_BYTE_SIZE_BS);
- let _: Vec<u8> = payload.trim_end(unsigned_metadata_size);
-
- payload.trim_end(DATA_PACKAGES_COUNT_BS)
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::{hex_to_bytes, read_payload_bytes, read_payload_hex},
- protocol::{
- constants::REDSTONE_MARKER_BS,
- payload::{trim_metadata, trim_payload, Payload},
- },
- };
-
- const PAYLOAD_METADATA_BYTES: &str = "000f000000";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTE: &str = "000f55000001";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTES: &str = "000f11223344556677889900aabbccddeeff000010";
-
- #[test]
- fn test_trim_metadata() {
- let prefix = "9e0294371c";
-
- for &bytes_str in &[
- PAYLOAD_METADATA_BYTES,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTE,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTES,
- ] {
- let mut bytes = hex_to_bytes(prefix.to_owned() + bytes_str);
- let result = trim_metadata(&mut bytes);
-
- assert_eq!(bytes, hex_to_bytes(prefix.into()));
- assert_eq!(result, 15);
- }
- }
-
- #[test]
- fn test_trim_payload() {
- let payload_hex = read_payload_bytes("./sample-data/payload.hex");
-
- let mut bytes = payload_hex[..payload_hex.len() - REDSTONE_MARKER_BS].into();
- let payload = trim_payload(&mut bytes);
-
- assert_eq!(bytes, Vec::<u8>::new());
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[test]
- fn test_make_payload() {
- let mut payload_hex = read_payload_bytes("./sample-data/payload.hex");
- let payload = Payload::make(&mut payload_hex);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[should_panic(expected = "Non empty payload remainder: 12")]
- #[test]
- fn test_make_payload_with_prefix() {
- let payload_hex = read_payload_hex("./sample-data/payload.hex");
- let mut bytes = hex_to_bytes("12".to_owned() + &payload_hex);
- let payload = Payload::make(&mut bytes);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-}
-
pub(crate) trait FilterSome<Output> {
- fn filter_some(&self) -> Output;
-}
-
-impl<T: Copy> FilterSome<Vec<T>> for [Option<T>] {
- fn filter_some(&self) -> Vec<T> {
- self.iter().filter_map(|&opt| opt).collect()
- }
-}
-
-#[cfg(test)]
-mod filter_some_tests {
- use crate::utils::filter::FilterSome;
-
- #[test]
- fn test_filter_some() {
- let values = [None, Some(23u64), None, Some(12), Some(12), None, Some(23)];
-
- assert_eq!(values.filter_some(), vec![23, 12, 12, 23])
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -
use crate::network::{assert::Assert, error::Error::ArrayIsEmpty, specific::U256};
-use std::ops::{Add, Rem, Shr};
-
-pub(crate) trait Median {
- type Item;
-
- fn median(self) -> Self::Item;
-}
-
-trait Avg {
- fn avg(self, other: Self) -> Self;
-}
-
-trait Averageable:
- Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy
-{
-}
-
-impl Averageable for i32 {}
-
-#[cfg(feature = "network_radix")]
-impl Avg for U256 {
- fn avg(self, other: Self) -> Self {
- let one = 1u32;
- let two = U256::from(2u8);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl Averageable for U256 {}
-
-impl<T> Avg for T
-where
- T: Averageable,
-{
- fn avg(self, other: Self) -> Self {
- let one = T::from(1);
- let two = T::from(2);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-impl<T> Median for Vec<T>
-where
- T: Copy + Ord + Avg,
-{
- type Item = T;
-
- fn median(self) -> Self::Item {
- let len = self.len();
-
- match len.assert_or_revert(|x| *x > 0, |_| ArrayIsEmpty) {
- 1 => self[0],
- 2 => self[0].avg(self[1]),
- 3 => maybe_pick_median(self[0], self[1], self[2]).unwrap_or_else(|| {
- maybe_pick_median(self[1], self[0], self[2])
- .unwrap_or_else(|| maybe_pick_median(self[1], self[2], self[0]).unwrap())
- }),
- _ => {
- let mut values = self;
- values.sort();
-
- let mid = len / 2;
-
- if len % 2 == 0 {
- values[mid - 1].avg(values[mid])
- } else {
- values[mid]
- }
- }
- }
- }
-}
-
-#[inline]
-fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>
-where
- T: PartialOrd,
-{
- if (b >= a && b <= c) || (b >= c && b <= a) {
- Some(b)
- } else {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{Avg, Median};
- use crate::network::specific::U256;
- use itertools::Itertools;
- use std::fmt::Debug;
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_avg() {
- let u256 = U256::max_value(); // 115792089237316195423570985008687907853269984665640564039457584007913129639935
- let u256_max_sub_1 = u256 - U256::from(1u32);
- let u256max_div_2 = u256 / U256::from(2u32);
-
- assert_eq!(u256.avg(U256::from(0u8)), u256max_div_2);
- assert_eq!(u256.avg(U256::from(1u8)), u256max_div_2 + U256::from(1u8));
- assert_eq!(u256.avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!(u256.avg(u256), u256);
-
- assert_eq!((u256_max_sub_1).avg(U256::from(0u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(U256::from(1u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!((u256_max_sub_1).avg(u256), u256_max_sub_1);
- }
-
- #[test]
- #[should_panic(expected = "Array is empty")]
- fn test_median_empty_vector() {
- let vec: Vec<i32> = vec![];
-
- vec.median();
- }
-
- #[test]
- fn test_median_single_element() {
- assert_eq!(vec![1].median(), 1);
- }
-
- #[test]
- fn test_median_two_elements() {
- test_all_permutations(vec![1, 3], 2);
- test_all_permutations(vec![1, 2], 1);
- test_all_permutations(vec![1, 1], 1);
- }
-
- #[test]
- fn test_median_three_elements() {
- test_all_permutations(vec![1, 2, 3], 2);
- test_all_permutations(vec![1, 1, 2], 1);
- test_all_permutations(vec![1, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1], 1);
- }
-
- #[test]
- fn test_median_even_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4], 2);
- test_all_permutations(vec![1, 2, 4, 4], 3);
- test_all_permutations(vec![1, 1, 3, 3], 2);
- test_all_permutations(vec![1, 1, 3, 4], 2);
- test_all_permutations(vec![1, 1, 1, 3], 1);
- test_all_permutations(vec![1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 1, 1, 1], 1);
- test_all_permutations(vec![1, 2, 3, 4, 5, 6], 3);
- }
-
- #[test]
- fn test_median_odd_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 1, 4, 5], 1);
- test_all_permutations(vec![1, 1, 1, 3, 3], 1);
- test_all_permutations(vec![1, 1, 3, 3, 5], 3);
-
- test_all_permutations(vec![1, 2, 3, 5, 5], 3);
- test_all_permutations(vec![1, 2, 5, 5, 5], 5);
- test_all_permutations(vec![1, 1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 3, 3, 5, 5], 3);
-
- test_all_permutations(vec![1, 2, 2, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1, 1, 2], 1);
- test_all_permutations(vec![1, 1, 1, 1, 1], 1);
-
- test_all_permutations(vec![1, 2, 3, 4, 5, 6, 7], 4);
- }
-
- fn test_all_permutations<T: Copy + Ord + Avg + Debug>(numbers: Vec<T>, expected_value: T) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
-
- for perm in perms {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- assert_eq!(p.median(), expected_value);
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -
use crate::network::{
- assert::Unwrap, error::Error, from_bytes_repr::FromBytesRepr, specific::U256,
-};
-
-pub trait Trim<T>
-where
- Self: Sized,
-{
- fn trim_end(&mut self, len: usize) -> T;
-}
-
-impl Trim<Vec<u8>> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> Self {
- if len >= self.len() {
- std::mem::take(self)
- } else {
- self.split_off(self.len() - len)
- }
- }
-}
-
-impl Trim<U256> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> U256 {
- U256::from_bytes_repr(self.trim_end(len))
- }
-}
-
-impl Trim<usize> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> usize {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-impl Trim<u64> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> u64 {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{
- network::specific::U256,
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
- };
-
- const MARKER_DECIMAL: u64 = 823907890102272;
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.into()
- }
-
- #[test]
- fn test_trim_end_number() {
- let (rest, result): (_, U256) = test_trim_end(3);
- assert_eq!(result, (256u32.pow(2) * 30).into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER[..6]);
-
- let (_, result): (_, u64) = test_trim_end(3);
- assert_eq!(result, 256u64.pow(2) * 30);
-
- let (_, result): (_, usize) = test_trim_end(3);
- assert_eq!(result, 256usize.pow(2) * 30);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(3);
- assert_eq!(result.as_slice(), &REDSTONE_MARKER[6..]);
- }
-
- #[test]
- fn test_trim_end_number_null() {
- let (rest, result): (_, U256) = test_trim_end(0);
- assert_eq!(result, 0u32.into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER);
-
- let (_, result): (_, u64) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, usize) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(0);
- assert_eq!(result, Vec::<u8>::new());
- }
-
- #[test]
- fn test_trim_end_whole() {
- test_trim_end_whole_size(REDSTONE_MARKER_BS);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 1);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 2);
- test_trim_end_whole_size(REDSTONE_MARKER_BS + 1);
- }
-
- fn test_trim_end_whole_size(size: usize) {
- let (rest, result): (_, U256) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL.into());
- assert_eq!(
- rest.as_slice().len(),
- REDSTONE_MARKER_BS - size.min(REDSTONE_MARKER_BS)
- );
-
- let (_, result): (_, u64) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL);
-
- let (_, result): (_, usize) = test_trim_end(size);
- assert_eq!(result, 823907890102272usize);
-
- let (_rest, result): (_, Vec<u8>) = test_trim_end(size);
- assert_eq!(result.as_slice().len(), size.min(REDSTONE_MARKER_BS));
- }
-
- #[test]
- fn test_trim_end_u64() {
- let mut bytes = vec![255, 255, 255, 255, 255, 255, 255, 255, 255];
- let x: u64 = bytes.trim_end(8);
-
- let expected_bytes = vec![255];
-
- assert_eq!(bytes, expected_bytes);
- assert_eq!(x, 18446744073709551615);
- }
-
- #[should_panic(expected = "Number overflow: 18591708106338011145")]
- #[test]
- fn test_trim_end_u64_overflow() {
- let mut bytes = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9];
-
- let _: u64 = bytes.trim_end(9);
- }
-
- #[allow(dead_code)]
- trait TestTrimEnd<T>
- where
- Self: Sized,
- {
- fn test_trim_end(size: usize) -> (Self, T);
- }
-
- fn test_trim_end<T>(size: usize) -> (Vec<u8>, T)
- where
- Vec<u8>: Trim<T>,
- {
- let mut bytes = redstone_marker_bytes();
- let rest = bytes.trim_end(size);
- (bytes, rest)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -
pub trait TrimZeros {
- fn trim_zeros(self) -> Self;
-}
-
-impl TrimZeros for Vec<u8> {
- fn trim_zeros(self) -> Self {
- let mut res = self.len();
-
- for i in (0..self.len()).rev() {
- if self[i] != 0 {
- break;
- }
-
- res = i;
- }
-
- let (rest, _) = self.split_at(res);
-
- rest.into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{protocol::constants::REDSTONE_MARKER, utils::trim_zeros::TrimZeros};
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.as_slice().into()
- }
-
- #[test]
- fn test_trim_zeros() {
- let trimmed = redstone_marker_bytes().trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
-
- let trimmed = trimmed.trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
- }
-
- #[test]
- fn test_trim_zeros_empty() {
- let trimmed = Vec::<u8>::default().trim_zeros();
- assert_eq!(trimmed, Vec::<u8>::default());
- }
-}
-
fn:
) to \
- restrict the search to a given item kind.","Accepted kinds are: fn
, mod
, struct
, \
- enum
, trait
, type
, macro
, \
- and const
.","Search functions by type signature (e.g., vec -> usize
or \
- -> vec
or String, enum:Cow -> bool
)","You can look for items with an exact name by putting double quotes around \
- your request: \"string\"
","Look for functions that accept or return \
- slices and \
- arrays by writing \
- square brackets (e.g., -> [u8]
or [] -> Option
)","Look for items inside another one by searching for a path: vec::Vec
",].map(x=>""+x+"
").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="${value.replaceAll(" ", " ")}
`}else{error[index]=value}});output+=`Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,\nas it avoids reallocation if possible. Additionally, if the element type\nT
overrides clone_from()
, this will reuse the resources of self
’s\nelements as well.
let x = vec![5, 6, 7];\nlet mut y = vec![8, 9, 10];\nlet yp: *const i32 = y.as_ptr();\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no reallocation occurred\nassert_eq!(yp, y.as_ptr());
TYPE_ID
should give a unique identifier for its SBOR schema type.\nAn SBOR schema type capture details about the SBOR payload, how it should be interpreted, validated and displayed. Read moreget_local_type_data
, we need to ensure that the type and all of its own references\nget added to the aggregator. Read moreExtend implementation that copies elements out of references before pushing them onto the Vec.
\nThis implementation is specialized for slice iterators, where it uses copy_from_slice
to\nappend the entire slice at once.
extend_one
)extend_one
)extend_one
)extend_one
)Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has\nconstant time complexity.
\nConvert a clone-on-write slice into a vector.
\nIf s
already owns a Vec<T>
, it will be returned directly.\nIf s
is borrowing a slice, a new Vec<T>
will be allocated and\nfilled by cloning s
’s items into it.
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);\nlet b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);\nassert_eq!(Vec::from(o), Vec::from(b));
Turn a VecDeque<T>
into a Vec<T>
.
This never needs to re-allocate, but does need to do O(n) data movement if\nthe circular buffer doesn’t happen to be at the beginning of the allocation.
\nuse std::collections::VecDeque;\n\n// This one is *O*(1).\nlet deque: VecDeque<_> = (1..5).collect();\nlet ptr = deque.as_slices().0.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);\n\n// This one needs data rearranging.\nlet mut deque: VecDeque<_> = (1..5).collect();\ndeque.push_front(9);\ndeque.push_front(8);\nlet ptr = deque.as_slices().1.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [8, 9, 1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);
Collects an iterator into a Vec, commonly called via Iterator::collect()
In general Vec
does not guarantee any particular growth or allocation strategy.\nThat also applies to this trait impl.
Note: This section covers implementation details and is therefore exempt from\nstability guarantees.
\nVec may use any or none of the following strategies,\ndepending on the supplied iterator:
\nIterator::size_hint()
\npushing
one item at a timeThe last case warrants some attention. It is an optimization that in many cases reduces peak memory\nconsumption and improves cache locality. But when big, short-lived allocations are created,\nonly a small fraction of their items get collected, no further use is made of the spare capacity\nand the resulting Vec
is moved into a longer-lived structure, then this can lead to the large\nallocations having their lifetimes unnecessarily extended which can result in increased memory\nfootprint.
In cases where this is an issue, the excess capacity can be discarded with Vec::shrink_to()
,\nVec::shrink_to_fit()
or by collecting into Box<[T]>
instead, which additionally reduces\nthe size of the long-lived struct.
static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());\n\nfor i in 0..10 {\n let big_temporary: Vec<u16> = (0..1024).collect();\n // discard most items\n let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();\n // without this a lot of unused capacity might be moved into the global\n result.shrink_to_fit();\n LONG_LIVED.lock().unwrap().push(result);\n}
The hash of a vector is the same as that of the corresponding slice,\nas required by the core::borrow::Borrow
implementation.
use std::hash::BuildHasher;\n\nlet b = std::hash::RandomState::new();\nlet v: Vec<u8> = vec![0xa8, 0x3c, 0x09];\nlet s: &[u8] = &[0xa8, 0x3c, 0x09];\nassert_eq!(b.hash_one(v), b.hash_one(s));
Creates a consuming iterator, that is, one that moves each value out of\nthe vector (from start to end). The vector cannot be used after calling\nthis.
\nlet v = vec![\"a\".to_string(), \"b\".to_string()];\nlet mut v_iter = v.into_iter();\n\nlet first_element: Option<String> = v_iter.next();\n\nassert_eq!(first_element, Some(\"a\".to_string()));\nassert_eq!(v_iter.next(), Some(\"b\".to_string()));\nassert_eq!(v_iter.next(), None);
Implements ordering of vectors, lexicographically.
\nImplements comparison of vectors, lexicographically.
\nself
and other
) and is used by the <=
\noperator. Read moreConstructs a new, empty Vec<T>
.
The vector will not allocate until elements are pushed onto it.
\nlet mut vec: Vec<i32> = Vec::new();
Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = Vec::with_capacity(10);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<()>::with_capacity(10);\nassert_eq!(vec_units.capacity(), usize::MAX);
try_with_capacity
)Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
Creates a Vec<T>
directly from a pointer, a length, and a capacity.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must have been allocated using the global allocator, such as via\nthe alloc::alloc
function.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to be the capacity that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is normally not safe\nto build a Vec<u8>
from a pointer to a C char
array with length\nsize_t
, doing so is only safe if the array was initially allocated by\na Vec
or String
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid\nthese issues, it is often preferable to do casting/transmuting using\nslice::from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
use std::ptr;\nuse std::mem;\n\nlet v = vec![1, 2, 3];\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts(p, len, cap);\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\nuse std::alloc::{alloc, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = alloc(layout).cast::<u32>();\n if mem.is_null() {\n return;\n }\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts(mem, 1, 16)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with value
.\nIf new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,\nin order to be able to clone the passed value.\nIf you need more flexibility (or want to rely on Default
instead of\nClone
), use Vec::resize_with
.\nIf you only need to resize to a smaller size, use Vec::truncate
.
let mut vec = vec![\"hello\"];\nvec.resize(3, \"world\");\nassert_eq!(vec, [\"hello\", \"world\", \"world\"]);\n\nlet mut vec = vec![1, 2, 3, 4];\nvec.resize(2, 0);\nassert_eq!(vec, [1, 2]);
Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends\nit to this Vec
. The other
slice is traversed in-order.
Note that this function is same as extend
except that it is\nspecialized to work with slices instead. If and when Rust gets\nspecialization this function will likely be deprecated (but still\navailable).
let mut vec = vec![1];\nvec.extend_from_slice(&[2, 3, 4]);\nassert_eq!(vec, [1, 2, 3, 4]);
Copies elements from src
range to the end of the vector.
Panics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut vec = vec![0, 1, 2, 3, 4];\n\nvec.extend_from_within(2..);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);\n\nvec.extend_from_within(..2);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);\n\nvec.extend_from_within(4..8);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
Creates a splicing iterator that replaces the specified range in the vector\nwith the given replace_with
iterator and yields the removed items.\nreplace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many elements are removed from the vector\nif the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
\nrange
) is empty,replace_with
yields fewer or equal elements than range
’s lengthsize_hint()
is exact.Otherwise, a temporary vector is allocated and the tail is moved twice.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut v = vec![1, 2, 3, 4];\nlet new = [7, 8, 9];\nlet u: Vec<_> = v.splice(1..3, new).collect();\nassert_eq!(v, &[1, 7, 8, 9, 4]);\nassert_eq!(u, &[2, 3]);
extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, then the element is removed and yielded.\nIf the closure returns false, the element will remain in the vector and will not be yielded\nby the iterator.
\nIf the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
\n\nlet mut i = 0;\nwhile i < vec.len() {\n if some_predicate(&mut vec[i]) {\n let val = vec.remove(i);\n // your code here\n } else {\n i += 1;\n }\n}\n
But extract_if
is easier to use. extract_if
is also more efficient,\nbecause it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate every element in the filter closure,\nregardless of whether you choose to keep or remove it.
Splitting an array into evens and odds, reusing the original allocation:
\n\n#![feature(extract_if)]\nlet mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];\n\nlet evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();\nlet odds = numbers;\n\nassert_eq!(evens, vec![2, 4, 6, 8, 14]);\nassert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
allocator_api
)Constructs a new, empty Vec<T, A>
.
The vector will not allocate until elements are pushed onto it.
\n#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec: Vec<i32, _> = Vec::new_in(System);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T, A>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec = Vec::with_capacity_in(10, System);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<(), System>::with_capacity_in(10, System);\nassert_eq!(vec_units.capacity(), usize::MAX);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
allocator_api
)Creates a Vec<T, A>
directly from a pointer, a length, a capacity,\nand an allocator.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must be currently allocated via the given allocator alloc
.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to fit the layout size that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T, A>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is not safe\nto build a Vec<u8>
from a pointer to a C char
array with length size_t
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nuse std::ptr;\nuse std::mem;\n\nlet mut v = Vec::with_capacity_in(3, System);\nv.push(1);\nv.push(2);\nv.push(3);\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\nlet alloc = v.allocator();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\n#![feature(allocator_api)]\n\nuse std::alloc::{AllocError, Allocator, Global, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = match Global.allocate(layout) {\n Ok(mem) => mem.cast::<u32>().as_ptr(),\n Err(AllocError) => return,\n };\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts_in(mem, 1, 16, Global)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
vec_into_raw_parts
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity)
.
Returns the raw pointer to the underlying data, the length of\nthe vector (in elements), and the allocated capacity of the\ndata (in elements). These are the same arguments in the same\norder as the arguments to from_raw_parts
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts
function, allowing\nthe destructor to perform the cleanup.
#![feature(vec_into_raw_parts)]\nlet v: Vec<i32> = vec![-1, 0, 1];\n\nlet (ptr, len, cap) = v.into_raw_parts();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts(ptr, len, cap)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
allocator_api
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity, allocator)
.
Returns the raw pointer to the underlying data, the length of the vector (in elements),\nthe allocated capacity of the data (in elements), and the allocator. These are the same\narguments in the same order as the arguments to from_raw_parts_in
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts_in
function, allowing\nthe destructor to perform the cleanup.
#![feature(allocator_api, vec_into_raw_parts)]\n\nuse std::alloc::System;\n\nlet mut v: Vec<i32, System> = Vec::new_in(System);\nv.push(-1);\nv.push(0);\nv.push(1);\n\nlet (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts_in(ptr, len, cap, alloc)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
Returns the total number of elements the vector can hold without\nreallocating.
\nlet mut vec: Vec<i32> = Vec::with_capacity(10);\nvec.push(42);\nassert!(vec.capacity() >= 10);
Reserves capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to\nspeculatively avoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve(10);\nassert!(vec.capacity() >= 11);
Reserves the minimum capacity for at least additional
more elements to\nbe inserted in the given Vec<T>
. Unlike reserve
, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact
, capacity will be greater than or equal to\nself.len() + additional
. Does nothing if the capacity is already\nsufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer reserve
if future insertions are expected.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve_exact(10);\nassert!(vec.capacity() >= 11);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to speculatively avoid\nfrequent reallocations. After calling try_reserve
, capacity will be\ngreater than or equal to self.len() + additional
if it returns\nOk(())
. Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Tries to reserve the minimum capacity for at least additional
\nelements to be inserted in the given Vec<T>
. Unlike try_reserve
,\nthis will not deliberately over-allocate to speculatively avoid frequent\nallocations. After calling try_reserve_exact
, capacity will be greater\nthan or equal to self.len() + additional
if it returns Ok(())
.\nDoes nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve
if future insertions are expected.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve_exact(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Shrinks the capacity of the vector as much as possible.
\nThe behavior of this method depends on the allocator, which may either shrink the vector\nin-place or reallocate. The resulting vector might still have some excess capacity, just as\nis the case for with_capacity
. See Allocator::shrink
for more details.
let mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to_fit();\nassert!(vec.capacity() >= 3);
Shrinks the capacity of the vector with a lower bound.
\nThe capacity will remain at least as large as both the length\nand the supplied value.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to(4);\nassert!(vec.capacity() >= 4);\nvec.shrink_to(0);\nassert!(vec.capacity() >= 3);
Converts the vector into Box<[T]>
.
Before doing the conversion, this method discards excess capacity like shrink_to_fit
.
let v = vec![1, 2, 3];\n\nlet slice = v.into_boxed_slice();
Any excess capacity is removed:
\n\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\n\nassert!(vec.capacity() >= 10);\nlet slice = vec.into_boxed_slice();\nassert_eq!(slice.into_vec().capacity(), 3);
Shortens the vector, keeping the first len
elements and dropping\nthe rest.
If len
is greater or equal to the vector’s current length, this has\nno effect.
The drain
method can emulate truncate
, but causes the excess\nelements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity\nof the vector.
\nTruncating a five element vector to two elements:
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nvec.truncate(2);\nassert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current\nlength:
let mut vec = vec![1, 2, 3];\nvec.truncate(8);\nassert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
\nmethod.
let mut vec = vec![1, 2, 3];\nvec.truncate(0);\nassert_eq!(vec, []);
Extracts a slice containing the entire vector.
\nEquivalent to &s[..]
.
use std::io::{self, Write};\nlet buffer = vec![1, 2, 3, 5, 8];\nio::sink().write(buffer.as_slice()).unwrap();
Extracts a mutable slice of the entire vector.
\nEquivalent to &mut s[..]
.
use std::io::{self, Read};\nlet mut buffer = vec![0; 3];\nio::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer\nvalid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThe caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell
) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize mutable references to the slice,\nor mutable references to specific elements you are planning on accessing through this pointer,\nas well as writing to those elements, may still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
let x = vec![1, 2, 4];\nlet x_ptr = x.as_ptr();\n\nunsafe {\n for i in 0..x.len() {\n assert_eq!(*x_ptr.add(i), 1 << i);\n }\n}
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0, 1, 2];\n let ptr1 = v.as_ptr();\n let _ = ptr1.read();\n let ptr2 = v.as_mut_ptr().offset(2);\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`\n // because it mutated a different element:\n let _ = ptr1.read();\n}
Returns an unsafe mutable pointer to the vector’s buffer, or a dangling\nraw pointer valid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThis method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize references to the slice,\nor references to specific elements you are planning on accessing through this pointer,\nmay still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
// Allocate vector big enough for 4 elements.\nlet size = 4;\nlet mut x: Vec<i32> = Vec::with_capacity(size);\nlet x_ptr = x.as_mut_ptr();\n\n// Initialize elements via raw pointer writes, then set length.\nunsafe {\n for i in 0..size {\n *x_ptr.add(i) = i as i32;\n }\n x.set_len(size);\n}\nassert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0];\n let ptr1 = v.as_mut_ptr();\n ptr1.write(1);\n let ptr2 = v.as_mut_ptr();\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`:\n ptr1.write(3);\n}
allocator_api
)Returns a reference to the underlying allocator.
\nForces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal\ninvariants of the type. Normally changing the length of a vector\nis done using one of the safe operations instead, such as\ntruncate
, resize
, extend
, or clear
.
new_len
must be less than or equal to capacity()
.old_len..new_len
must be initialized.This method can be useful for situations in which the vector\nis serving as a buffer for other code, particularly over FFI:
\n\npub fn get_dictionary(&self) -> Option<Vec<u8>> {\n // Per the FFI method's docs, \"32768 bytes is always enough\".\n let mut dict = Vec::with_capacity(32_768);\n let mut dict_length = 0;\n // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:\n // 1. `dict_length` elements were initialized.\n // 2. `dict_length` <= the capacity (32_768)\n // which makes `set_len` safe to call.\n unsafe {\n // Make the FFI call...\n let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);\n if r == Z_OK {\n // ...and update the length to what was initialized.\n dict.set_len(dict_length);\n Some(dict)\n } else {\n None\n }\n }\n}
While the following example is sound, there is a memory leak since\nthe inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],\n vec![0, 1, 0],\n vec![0, 0, 1]];\n// SAFETY:\n// 1. `old_len..0` is empty so no elements need to be initialized.\n// 2. `0 <= capacity` always holds whatever `capacity` is.\nunsafe {\n vec.set_len(0);\n}
Normally, here, one would use clear
instead to correctly drop\nthe contents and thus not leak memory.
Removes an element from the vector and returns it.
\nThe removed element is replaced by the last element of the vector.
\nThis does not preserve ordering of the remaining elements, but is O(1).\nIf you need to preserve the element order, use remove
instead.
Panics if index
is out of bounds.
let mut v = vec![\"foo\", \"bar\", \"baz\", \"qux\"];\n\nassert_eq!(v.swap_remove(1), \"bar\");\nassert_eq!(v, [\"foo\", \"qux\", \"baz\"]);\n\nassert_eq!(v.swap_remove(0), \"foo\");\nassert_eq!(v, [\"baz\", \"qux\"]);
Inserts an element at position index
within the vector, shifting all\nelements after it to the right.
Panics if index > len
.
let mut vec = vec![1, 2, 3];\nvec.insert(1, 4);\nassert_eq!(vec, [1, 4, 2, 3]);\nvec.insert(4, 5);\nassert_eq!(vec, [1, 4, 2, 3, 5]);
Takes O(Vec::len
) time. All items after the insertion index must be\nshifted to the right. In the worst case, all elements are shifted when\nthe insertion index is 0.
Removes and returns the element at position index
within the vector,\nshifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a\nworst-case performance of O(n). If you don’t need the order of elements\nto be preserved, use swap_remove
instead. If you’d like to remove\nelements from the beginning of the Vec
, consider using\nVecDeque::pop_front
instead.
Panics if index
is out of bounds.
let mut v = vec![1, 2, 3];\nassert_eq!(v.remove(1), 2);\nassert_eq!(v, [1, 3]);
Retains only the elements specified by the predicate.
\nIn other words, remove all elements e
for which f(&e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain(|&x| x % 2 == 0);\nassert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\nvec.retain(|_| *iter.next().unwrap());\nassert_eq!(vec, [2, 3, 5]);
Retains only the elements specified by the predicate, passing a mutable reference to it.
\nIn other words, remove all elements e
such that f(&mut e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain_mut(|x| if *x <= 3 {\n *x += 1;\n true\n} else {\n false\n});\nassert_eq!(vec, [2, 3, 4]);
Removes all but the first of consecutive elements in the vector that resolve to the same\nkey.
\nIf the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![10, 20, 21, 30, 20];\n\nvec.dedup_by_key(|i| *i / 10);\n\nassert_eq!(vec, [10, 20, 30, 20]);
Removes all but the first of consecutive elements in the vector satisfying a given equality\nrelation.
\nThe same_bucket
function is passed references to two elements from the vector and\nmust determine if the elements compare equal. The elements are passed in opposite order\nfrom their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![\"foo\", \"bar\", \"Bar\", \"baz\", \"bar\"];\n\nvec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));\n\nassert_eq!(vec, [\"foo\", \"bar\", \"baz\", \"bar\"]);
Appends an element to the back of a collection.
\nPanics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1, 2];\nvec.push(3);\nassert_eq!(vec, [1, 2, 3]);
Takes amortized O(1) time. If the vector’s length would exceed its\ncapacity after the push, O(capacity) time is taken to copy the\nvector’s elements to a larger allocation. This expensive operation is\noffset by the capacity O(1) insertions it allows.
\nvec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned\nwith the element.
\nUnlike push
this method will not reallocate when there’s insufficient capacity.\nThe caller should use reserve
or try_reserve
to ensure that there is enough capacity.
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]\n\nuse std::collections::TryReserveError;\nfn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {\n let mut vec = Vec::new();\n for value in iter {\n if let Err(value) = vec.push_within_capacity(value) {\n vec.try_reserve(1)?;\n // this cannot fail, the previous line either returned or added at least 1 free slot\n let _ = vec.push_within_capacity(value);\n }\n }\n Ok(vec)\n}\nassert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
Takes O(1) time.
\nRemoves the last element from a vector and returns it, or None
if it\nis empty.
If you’d like to pop the first element, consider using\nVecDeque::pop_front
instead.
let mut vec = vec![1, 2, 3];\nassert_eq!(vec.pop(), Some(3));\nassert_eq!(vec, [1, 2]);
Takes O(1) time.
\nvec_pop_if
)Removes and returns the last element in a vector if the predicate\nreturns true
, or None
if the predicate returns false or the vector\nis empty.
#![feature(vec_pop_if)]\n\nlet mut vec = vec![1, 2, 3, 4];\nlet pred = |x: &mut i32| *x % 2 == 0;\n\nassert_eq!(vec.pop_if(pred), Some(4));\nassert_eq!(vec, [1, 2, 3]);\nassert_eq!(vec.pop_if(pred), None);
Removes the specified range from the vector in bulk, returning all\nremoved elements as an iterator. If the iterator is dropped before\nbeing fully consumed, it drops the remaining removed elements.
\nThe returned iterator keeps a mutable borrow on the vector to optimize\nits implementation.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nIf the returned iterator goes out of scope without being dropped (due to\nmem::forget
, for example), the vector may have lost and leaked\nelements arbitrarily, including elements outside the range.
let mut v = vec![1, 2, 3];\nlet u: Vec<_> = v.drain(1..).collect();\nassert_eq!(v, &[1]);\nassert_eq!(u, &[2, 3]);\n\n// A full range clears the vector, like `clear()` does\nv.drain(..);\nassert_eq!(v, &[]);
Clears the vector, removing all values.
\nNote that this method has no effect on the allocated capacity\nof the vector.
\nlet mut v = vec![1, 2, 3];\n\nv.clear();\n\nassert!(v.is_empty());
Returns the number of elements in the vector, also referred to\nas its ‘length’.
\nlet a = vec![1, 2, 3];\nassert_eq!(a.len(), 3);
Returns true
if the vector contains no elements.
let mut v = Vec::new();\nassert!(v.is_empty());\n\nv.push(1);\nassert!(!v.is_empty());
Splits the collection into two at the given index.
\nReturns a newly allocated vector containing the elements in the range\n[at, len)
. After the call, the original vector will be left containing\nthe elements [0, at)
with its previous capacity unchanged.
mem::take
or mem::replace
.Vec::truncate
.Vec::drain
.Panics if at > len
.
let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with the result of\ncalling the closure f
. The return values from f
will end up\nin the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If\nyou’d rather Clone
a given value, use Vec::resize
. If you\nwant to use the Default
trait to generate values, you can\npass Default::default
as the second argument.
let mut vec = vec![1, 2, 3];\nvec.resize_with(5, Default::default);\nassert_eq!(vec, [1, 2, 3, 0, 0]);\n\nlet mut vec = vec![];\nlet mut p = 1;\nvec.resize_with(4, || { p *= 2; p });\nassert_eq!(vec, [2, 4, 8, 16]);
Consumes and leaks the Vec
, returning a mutable reference to the contents,\n&'a mut [T]
. Note that the type T
must outlive the chosen lifetime\n'a
. If the type has only static references, or none at all, then this\nmay be chosen to be 'static
.
As of Rust 1.57, this method does not reallocate or shrink the Vec
,\nso the leaked allocation may include unused capacity that is not part\nof the returned slice.
This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak.
\nSimple usage:
\n\nlet x = vec![1, 2, 3];\nlet static_ref: &'static mut [usize] = x.leak();\nstatic_ref[0] += 1;\nassert_eq!(static_ref, &[2, 2, 3]);
Returns the remaining spare capacity of the vector as a slice of\nMaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by\nreading from a file) before marking the data as initialized using the\nset_len
method.
// Allocate vector big enough for 10 elements.\nlet mut v = Vec::with_capacity(10);\n\n// Fill in the first 3 elements.\nlet uninit = v.spare_capacity_mut();\nuninit[0].write(0);\nuninit[1].write(1);\nuninit[2].write(2);\n\n// Mark the first 3 elements of the vector as being initialized.\nunsafe {\n v.set_len(3);\n}\n\nassert_eq!(&v, &[0, 1, 2]);
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare\ncapacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data\n(e.g. by reading from a file) before marking the data as initialized using\nthe set_len
method.
Note that this is a low-level API, which should be used with care for\noptimization purposes. If you need to append data to a Vec
\nyou can use push
, extend
, extend_from_slice
,\nextend_from_within
, insert
, append
, resize
or\nresize_with
, depending on your exact needs.
#![feature(vec_split_at_spare)]\n\nlet mut v = vec![1, 1, 2];\n\n// Reserve additional space big enough for 10 elements.\nv.reserve(10);\n\nlet (init, uninit) = v.split_at_spare_mut();\nlet sum = init.iter().copied().sum::<u32>();\n\n// Fill in the next 4 elements.\nuninit[0].write(sum);\nuninit[1].write(sum * 2);\nuninit[2].write(sum * 3);\nuninit[3].write(sum * 4);\n\n// Mark the 4 elements of the vector as being initialized.\nunsafe {\n let len = v.len();\n v.set_len(len + 4);\n}\n\nassert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
pub(crate) fn aggregate_values(
- config: Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<U256>
Aggregates values from a collection of data packages according to the provided configuration.
-This function takes a configuration and a vector of data packages, constructs a matrix of values
-and their corresponding signers, and then aggregates these values based on the aggregation logic
-defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-an average of the values, selecting the median, or applying a custom algorithm defined within the
-aggregate_matrix
function.
The primary purpose of this function is to consolidate data from multiple sources into a coherent
-and singular value set that adheres to the criteria specified in the Config
.
config
- A Config
instance containing settings and parameters used to guide the aggregation process.data_packages
- A vector of DataPackage
instances, each representing a set of values and associated
-metadata collected from various sources or signers.Returns a Vec<U256>
, which is a vector of aggregated values resulting from applying the aggregation
-logic to the input data packages as per the specified configuration. Each U256
value in the vector
-represents an aggregated result derived from the corresponding data packages.
This function is internal to the crate (pub(crate)
) and not exposed as part of the public API. It is
-designed to be used by other components within the same crate that require value aggregation functionality.
fn make_value_signer_matrix(
- config: &Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<Vec<Option<U256>>>
pub struct Config {
- pub signer_count_threshold: u8,
- pub signers: Vec<Bytes>,
- pub feed_ids: Vec<U256>,
- pub block_timestamp: u64,
-}
Configuration for a RedStone payload processor.
-Specifies the parameters necessary for the verification and aggregation of values -from various data points passed by the RedStone payload.
-signer_count_threshold: u8
The minimum number of signers required validating the data.
-Specifies how many unique signers (from different addresses) are required -for the data to be considered valid and trustworthy.
-signers: Vec<Bytes>
List of identifiers for signers authorized to sign the data.
-Each signer is identified by a unique, network-specific byte string (Bytes
),
-which represents their address.
feed_ids: Vec<U256>
Identifiers for the data feeds from which values are aggregated.
-Each data feed id is represented by the network-specific U256
type.
block_timestamp: u64
The current block time in timestamp format, used for verifying data timeliness.
-The value’s been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows -for determining whether the data is current in the context of blockchain time.
-self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morefn make_processor_result(config: Config, payload: Payload) -> ProcessorResult
pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult
The main processor of the RedStone payload.
-config
- Configuration of the payload processing.payload_bytes
- Network-specific byte-list of the payload to be processed.pub struct ProcessorResult {
- pub min_timestamp: u64,
- pub values: Vec<U256>,
-}
Represents the result of processing the RedStone payload.
-This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-particularly focusing on time-sensitive data and its associated values, according to the Config
.
min_timestamp: u64
The minimum timestamp encountered during processing.
-This field captures the earliest time point (in milliseconds since the Unix epoch) -among the processed data packages, indicating the starting boundary of the dataset’s time range.
-values: Vec<U256>
A collection of values processed during the operation.
-Each element in this vector represents a processed value corresponding
-to the passed data_feed item in the Config
.
self
and other
values to be equal, and is used
-by ==
.self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.pub(crate) trait Validator {
- // Required methods
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
- fn validate_signer_count_threshold(
- &self,
- index: usize,
- values: &[Option<U256>],
- ) -> Vec<U256>;
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
A trait defining validation operations for data feeds and signers.
-This trait specifies methods for validating aspects of data feeds and signers within a system that -requires data integrity and authenticity checks. Implementations of this trait are responsible for -defining the logic behind each validation step, ensuring that data conforms to expected rules and -conditions.
-Retrieves the index of a given data feed.
-This method takes a feed_id
representing the unique identifier of a data feed and
-returns an Option<usize>
indicating the index of the feed within a collection of feeds.
-If the feed does not exist, None
is returned.
feed_id
: U256
- The unique identifier of the data feed.Option<usize>
- The index of the feed if it exists, or None
if it does not.Retrieves the index of a given signer.
-This method accepts a signer identifier in the form of a byte slice and returns an
-Option<usize>
indicating the signer’s index within a collection of signers. If the signer
-is not found, None
is returned.
signer
: &[u8]
- A byte slice representing the signer’s identifier.Option<usize>
- The index of the signer if found, or None
if not found.Validates the signer count threshold for a given index within a set of values.
-This method is responsible for ensuring that the number of valid signers meets or exceeds
-a specified threshold necessary for a set of data values to be considered valid. It returns
-a vector of U256
if the values pass the validation, to be processed in other steps.
index
: usize
- The index of the data value being validated.values
: &[Option<U256>]
- A slice of optional U256
values associated with the data.Vec<U256>
- A vector of U256
values that meet the validation criteria.Validates the timestamp for a given index.
-This method checks whether a timestamp associated with a data value at a given index -meets specific conditions (e.g., being within an acceptable time range). It returns -the validated timestamp if it’s valid, to be processed in other steps.
-index
: usize
- The index of the data value whose timestamp is being validated.timestamp
: u64
- The timestamp to be validated.u64
- The validated timestamp.redstone
is a collection of utilities to make deserializing&decrypting RedStone payload.
-It includes a pure Rust implementation, along with extensions for certain networks.
Different crypto-mechanisms are easily injectable.
-The current implementation contains secp256k1
- and k256
-based variants.
Redirecting to macro.print_and_panic.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_and_panic.html b/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_and_panic.html deleted file mode 100644 index b308eb68..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_and_panic.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_and_panic { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
Redirecting to macro.print_debug.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_debug.html b/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_debug.html deleted file mode 100644 index 3cb863d6..00000000 --- a/static/rust/redstone/crypto_secp256k1,network_radix/redstone/macro.print_debug.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_debug { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
pub trait AsAsciiStr {
- // Required method
- fn as_ascii_str(&self) -> String;
-}
pub trait AsHexStr {
- // Required method
- fn as_hex_str(&self) -> String;
-}
pub trait Assert<F> {
- // Required method
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
pub trait Unwrap<R> {
- type ErrorArg;
-
- // Required method
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
pub enum Error {
- ContractError(Box<dyn ContractErrorContent>),
- NumberOverflow(U256),
- ArrayIsEmpty,
- CryptographicError(usize),
- SizeNotSupported(usize),
- WrongRedStoneMarker(Vec<u8>),
- NonEmptyPayloadRemainder(Vec<u8>),
- InsufficientSignerCount(usize, usize, U256),
- TimestampTooOld(usize, u64),
- TimestampTooFuture(usize, u64),
- ClonedContractError(u8, String),
-}
Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-These errors include issues with contract logic, data types, -cryptographic operations, and conditions specific to the requirements.
-Represents errors that arise from the contract itself.
-This variant is used for encapsulating errors that are specific to the contract’s logic -or execution conditions that aren’t covered by more specific error types.
-Indicates an overflow error with U256
numbers.
Used when operations on U256
numbers exceed their maximum value, potentially leading
-to incorrect calculations or state.
Used when an expected non-empty array or vector is found to be empty.
-This could occur in scenarios where the contract logic requires a non-empty collection -of items for the correct operation, for example, during aggregating the values.
-Represents errors related to cryptographic operations.
-This includes failures in signature verification, hashing, or other cryptographic -processes, with the usize indicating the position or identifier of the failed operation.
-Signifies that an unsupported size was encountered.
-This could be used when a data structure or input does not meet the expected size -requirements for processing.
-Indicates that the marker bytes for RedStone are incorrect.
-This error is specific to scenarios where marker or identifier bytes do not match -expected values, potentially indicating corrupted or tampered data.
-Used when there is leftover data in a payload that should have been empty.
-This could indicate an error in data parsing or that additional, unexpected data -was included in a message or transaction.
-Indicates that the number of signers does not meet the required threshold.
-This variant includes the current number of signers, the required threshold, and -potentially a feed_id related to the operation that failed due to insufficient signers.
-Used when a timestamp is older than allowed by the processor logic.
-Includes the position or identifier of the timestamp and the threshold value, -indicating that the provided timestamp is too far in the past.
-Indicates that a timestamp is further in the future than allowed.
-Similar to TimestampTooOld
, but for future timestamps exceeding the contract’s
-acceptance window.
Represents errors that need to clone ContractErrorContent
, which is not supported by default.
This variant allows for the manual duplication of contract error information, including -an error code and a descriptive message.
-self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub trait FromBytesRepr<T> {
- // Required method
- fn from_bytes_repr(bytes: T) -> Self;
-}
pub struct Radix;
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- // Required methods
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage
pub(crate) fn trim_data_packages(
- payload: &mut Vec<u8>,
- count: usize,
-) -> Vec<DataPackage>
pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
signer_address: Vec<u8>
§timestamp: u64
§data_points: Vec<DataPoint>
source
. Read moreself
and other
values to be equal, and is used
-by ==
.self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint
pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
feed_id: U256
§value: U256
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morekey
and return true
if they are equal.pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
data_packages: Vec<DataPackage>
self
to type T
. The semantics of numeric casting with the as
operator are followed, so <T as As>::as_::<U>
can be used in the same way as T as U
for numeric conversions. Read morepub(crate) trait FilterSome<Output> {
- // Required method
- fn filter_some(&self) -> Output;
-}
fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>where
- T: PartialOrd,
pub trait TrimZeros {
- // Required method
- fn trim_zeros(self) -> Self;
-}
U::from(self)
.\nThe minimum number of signers required validating the data.\nList of identifiers for signers authorized to sign the …\nThe main processor of the RedStone payload.\nRepresents the result of processing the RedStone payload.\nReturns the argument unchanged.\nCalls U::from(self)
.\nThe minimum timestamp encountered during processing.\nA collection of values processed during the operation.\nA trait defining validation operations for data feeds and …\nRetrieves the index of a given data feed.\nRetrieves the index of a given signer.\nValidates the signer count threshold for a given index …\nValidates the timestamp for a given index.\nUsed when an expected non-empty array or vector is found …\nRepresents errors that need to clone ContractErrorContent
, …\nRepresents errors that arise from the contract itself.\nRepresents errors related to cryptographic operations.\nErrors that can be encountered in the …\nIndicates that the number of signers does not meet the …\nUsed when there is leftover data in a payload that should …\nIndicates an overflow error with U256
numbers.\nSignifies that an unsupported size was encountered.\nIndicates that a timestamp is further in the future than …\nUsed when a timestamp is older than allowed by the …\nIndicates that the marker bytes for RedStone are incorrect.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.")
\ No newline at end of file
diff --git a/static/rust/redstone/crypto_secp256k1,network_radix/settings.html b/static/rust/redstone/crypto_secp256k1,network_radix/settings.html
deleted file mode 100644
index 9631dcb2..00000000
--- a/static/rust/redstone/crypto_secp256k1,network_radix/settings.html
+++ /dev/null
@@ -1 +0,0 @@
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -
use crate::{
- core::{config::Config, validator::Validator},
- network::specific::U256,
- print_debug,
- protocol::data_package::DataPackage,
- utils::median::Median,
-};
-
-type Matrix = Vec<Vec<Option<U256>>>;
-
-/// Aggregates values from a collection of data packages according to the provided configuration.
-///
-/// This function takes a configuration and a vector of data packages, constructs a matrix of values
-/// and their corresponding signers, and then aggregates these values based on the aggregation logic
-/// defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-/// an average of the values, selecting the median, or applying a custom algorithm defined within the
-/// `aggregate_matrix` function.
-///
-/// The primary purpose of this function is to consolidate data from multiple sources into a coherent
-/// and singular value set that adheres to the criteria specified in the `Config`.
-///
-/// # Arguments
-///
-/// * `config` - A `Config` instance containing settings and parameters used to guide the aggregation process.
-/// * `data_packages` - A vector of `DataPackage` instances, each representing a set of values and associated
-/// metadata collected from various sources or signers.
-///
-/// # Returns
-///
-/// Returns a `Vec<U256>`, which is a vector of aggregated values resulting from applying the aggregation
-/// logic to the input data packages as per the specified configuration. Each `U256` value in the vector
-/// represents an aggregated result derived from the corresponding data packages.
-///
-/// # Note
-///
-/// This function is internal to the crate (`pub(crate)`) and not exposed as part of the public API. It is
-/// designed to be used by other components within the same crate that require value aggregation functionality.
-pub(crate) fn aggregate_values(config: Config, data_packages: Vec<DataPackage>) -> Vec<U256> {
- aggregate_matrix(make_value_signer_matrix(&config, data_packages), config)
-}
-
-fn aggregate_matrix(matrix: Matrix, config: Config) -> Vec<U256> {
- matrix
- .iter()
- .enumerate()
- .map(|(index, values)| {
- config
- .validate_signer_count_threshold(index, values)
- .median()
- })
- .collect()
-}
-
-fn make_value_signer_matrix(config: &Config, data_packages: Vec<DataPackage>) -> Matrix {
- let mut matrix = vec![vec![None; config.signers.len()]; config.feed_ids.len()];
-
- data_packages.iter().for_each(|data_package| {
- if let Some(signer_index) = config.signer_index(&data_package.signer_address) {
- data_package.data_points.iter().for_each(|data_point| {
- if let Some(feed_index) = config.feed_index(data_point.feed_id) {
- matrix[feed_index][signer_index] = data_point.value.into()
- }
- })
- }
- });
-
- print_debug!("{:?}", matrix);
-
- matrix
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod aggregate_matrix_tests {
- use crate::{
- core::{aggregator::aggregate_matrix, config::Config},
- helpers::iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- };
-
- #[test]
- fn test_aggregate_matrix() {
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8, 23].iter_into_opt(),
- ];
-
- for signer_count_threshold in 0..Config::test().signers.len() + 1 {
- let mut config = Config::test();
- config.signer_count_threshold = signer_count_threshold as u8;
-
- let result = aggregate_matrix(matrix.clone(), config);
-
- assert_eq!(result, vec![12u8, 22].iter_into());
- }
- }
-
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_one_value() {
- let mut config = Config::test();
- config.signer_count_threshold = 1;
-
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8.into(), None].opt_iter_into_opt(),
- ];
-
- let result = aggregate_matrix(matrix, config);
-
- assert_eq!(result, vec![12u8, 21].iter_into());
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_whole_feed() {
- let mut config = Config::test();
- config.signer_count_threshold = 0;
-
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, config);
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #0 (ETH)")]
- #[test]
- fn test_aggregate_matrix_missing_one_value() {
- let matrix = vec![
- vec![21u8.into(), None].opt_iter_into_opt(),
- vec![11u8, 12].iter_into_opt(),
- ];
-
- aggregate_matrix(matrix, Config::test());
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #1 (BTC)")]
- #[test]
- fn test_aggregate_matrix_missing_whole_feed() {
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, Config::test());
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod make_value_signer_matrix {
- use crate::{
- core::{
- aggregator::{make_value_signer_matrix, Matrix},
- config::Config,
- test_helpers::{AVAX, BTC, ETH, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2},
- },
- helpers::iter_into::IterInto,
- network::specific::U256,
- protocol::data_package::DataPackage,
- };
-
- #[test]
- fn test_make_value_signer_matrix_empty() {
- let config = Config::test();
-
- test_make_value_signer_matrix_of(
- vec![],
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_exact() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_greater() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_smaller() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_diagonal() {
- let data_packages = vec![
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11.into(), None], vec![None, 22.into()]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_repetitions() {
- let data_packages = vec![
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 202, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 101, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![101, 12].iter_into(), vec![21, 202].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_all_wrong() {
- let config = Config::test();
-
- let data_packages = vec![
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_mix() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- fn test_make_value_signer_matrix_of(
- data_packages: Vec<DataPackage>,
- expected_values: Vec<Vec<Option<u128>>>,
- ) {
- let config = &Config::test();
- let result = make_value_signer_matrix(config, data_packages);
-
- let expected_matrix: Matrix = expected_values
- .iter()
- .map(|row| {
- (row.iter()
- .map(|&value| value.map(U256::from))
- .collect::<Vec<_>>())
- .iter_into() as Vec<Option<U256>>
- })
- .collect();
-
- assert_eq!(result, expected_matrix)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -
use crate::network::specific::{Bytes, U256};
-
-/// Configuration for a RedStone payload processor.
-///
-/// Specifies the parameters necessary for the verification and aggregation of values
-/// from various data points passed by the RedStone payload.
-#[derive(Debug)]
-pub struct Config {
- /// The minimum number of signers required validating the data.
- ///
- /// Specifies how many unique signers (from different addresses) are required
- /// for the data to be considered valid and trustworthy.
- pub signer_count_threshold: u8,
-
- /// List of identifiers for signers authorized to sign the data.
- ///
- /// Each signer is identified by a unique, network-specific byte string (`Bytes`),
- /// which represents their address.
- pub signers: Vec<Bytes>,
-
- /// Identifiers for the data feeds from which values are aggregated.
- ///
- /// Each data feed id is represented by the network-specific `U256` type.
- pub feed_ids: Vec<U256>,
-
- /// The current block time in timestamp format, used for verifying data timeliness.
- ///
- /// The value's been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows
- /// for determining whether the data is current in the context of blockchain time.
- pub block_timestamp: u64,
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -
use crate::{
- core::{
- aggregator::aggregate_values, config::Config, processor_result::ProcessorResult,
- validator::Validator,
- },
- network::specific::Bytes,
- print_debug,
- protocol::payload::Payload,
-};
-
-/// The main processor of the RedStone payload.
-///
-///
-/// # Arguments
-///
-/// * `config` - Configuration of the payload processing.
-/// * `payload_bytes` - Network-specific byte-list of the payload to be processed.
-pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult {
- #[allow(clippy::useless_conversion)]
- let mut bytes: Vec<u8> = payload_bytes.into();
- let payload = Payload::make(&mut bytes);
- print_debug!("{:?}", payload);
-
- make_processor_result(config, payload)
-}
-
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult {
- let min_timestamp = payload
- .data_packages
- .iter()
- .enumerate()
- .map(|(index, dp)| config.validate_timestamp(index, dp.timestamp))
- .min()
- .unwrap();
-
- let values = aggregate_values(config, payload.data_packages);
-
- print_debug!("{} {:?}", min_timestamp, values);
-
- ProcessorResult {
- values,
- min_timestamp,
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- processor::make_processor_result,
- processor_result::ProcessorResult,
- test_helpers::{
- BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- },
- helpers::iter_into::IterInto,
- protocol::{data_package::DataPackage, payload::Payload},
- };
-
- #[test]
- fn test_make_processor_result() {
- let data_packages = vec![
- DataPackage::test(
- ETH,
- 11,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 5).into(),
- ),
- DataPackage::test(
- ETH,
- 13,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP + 3).into(),
- ),
- DataPackage::test(
- BTC,
- 32,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP - 2).into(),
- ),
- DataPackage::test(
- BTC,
- 31,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 400).into(),
- ),
- ];
-
- let result = make_processor_result(Config::test(), Payload { data_packages });
-
- assert_eq!(
- result,
- ProcessorResult {
- min_timestamp: TEST_BLOCK_TIMESTAMP - 2,
- values: vec![12u8, 31].iter_into()
- }
- );
- }
-}
-
use crate::network::specific::U256;
-
-/// Represents the result of processing the RedStone payload.
-///
-/// This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-/// particularly focusing on time-sensitive data and its associated values, according to the `Config`.
-#[derive(Debug, Eq, PartialEq)]
-pub struct ProcessorResult {
- /// The minimum timestamp encountered during processing.
- ///
- /// This field captures the earliest time point (in milliseconds since the Unix epoch)
- /// among the processed data packages, indicating the starting boundary of the dataset's time range.
- pub min_timestamp: u64,
-
- /// A collection of values processed during the operation.
- ///
- /// Each element in this vector represents a processed value corresponding
- /// to the passed data_feed item in the `Config`.
- pub values: Vec<U256>,
-}
-
-impl From<ProcessorResult> for (u64, Vec<U256>) {
- fn from(result: ProcessorResult) -> Self {
- (result.min_timestamp, result.values)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -
use crate::{
- core::config::Config,
- network::{
- assert::Assert,
- error::Error::{InsufficientSignerCount, TimestampTooFuture, TimestampTooOld},
- specific::U256,
- },
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- utils::filter::FilterSome,
-};
-
-/// A trait defining validation operations for data feeds and signers.
-///
-/// This trait specifies methods for validating aspects of data feeds and signers within a system that
-/// requires data integrity and authenticity checks. Implementations of this trait are responsible for
-/// defining the logic behind each validation step, ensuring that data conforms to expected rules and
-/// conditions.
-pub(crate) trait Validator {
- /// Retrieves the index of a given data feed.
- ///
- /// This method takes a `feed_id` representing the unique identifier of a data feed and
- /// returns an `Option<usize>` indicating the index of the feed within a collection of feeds.
- /// If the feed does not exist, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `feed_id`: `U256` - The unique identifier of the data feed.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the feed if it exists, or `None` if it does not.
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
-
- /// Retrieves the index of a given signer.
- ///
- /// This method accepts a signer identifier in the form of a byte slice and returns an
- /// `Option<usize>` indicating the signer's index within a collection of signers. If the signer
- /// is not found, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `signer`: `&[u8]` - A byte slice representing the signer's identifier.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the signer if found, or `None` if not found.
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
-
- /// Validates the signer count threshold for a given index within a set of values.
- ///
- /// This method is responsible for ensuring that the number of valid signers meets or exceeds
- /// a specified threshold necessary for a set of data values to be considered valid. It returns
- /// a vector of `U256` if the values pass the validation, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value being validated.
- /// * `values`: `&[Option<U256>]` - A slice of optional `U256` values associated with the data.
- ///
- /// # Returns
- ///
- /// * `Vec<U256>` - A vector of `U256` values that meet the validation criteria.
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256>;
-
- /// Validates the timestamp for a given index.
- ///
- /// This method checks whether a timestamp associated with a data value at a given index
- /// meets specific conditions (e.g., being within an acceptable time range). It returns
- /// the validated timestamp if it's valid, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value whose timestamp is being validated.
- /// * `timestamp`: `u64` - The timestamp to be validated.
- ///
- /// # Returns
- ///
- /// * `u64` - The validated timestamp.
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
-
-impl Validator for Config {
- #[inline]
- fn feed_index(&self, feed_id: U256) -> Option<usize> {
- self.feed_ids.iter().position(|&elt| elt == feed_id)
- }
-
- #[inline]
- fn signer_index(&self, signer: &[u8]) -> Option<usize> {
- self.signers
- .iter()
- .position(|elt| elt.to_ascii_lowercase() == signer.to_ascii_lowercase())
- }
-
- #[inline]
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256> {
- values.filter_some().assert_or_revert(
- |x| (*x).len() >= self.signer_count_threshold.into(),
- #[allow(clippy::useless_conversion)]
- |val| InsufficientSignerCount(index, val.len(), self.feed_ids[index]),
- )
- }
-
- #[inline]
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64 {
- timestamp.assert_or_revert(
- |&x| x + MAX_TIMESTAMP_DELAY_MS >= self.block_timestamp,
- |timestamp| TimestampTooOld(index, *timestamp),
- );
-
- timestamp.assert_or_revert(
- |&x| x <= self.block_timestamp + MAX_TIMESTAMP_AHEAD_MS,
- |timestamp| TimestampTooFuture(index, *timestamp),
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- test_helpers::{
- AVAX, BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- validator::Validator,
- },
- helpers::{
- hex::{hex_to_bytes, make_feed_id},
- iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- },
- network::specific::U256,
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- };
- use itertools::Itertools;
-
- #[test]
- fn test_feed_index() {
- let config = Config::test();
-
- let eth_index = config.feed_index(make_feed_id(ETH));
- assert_eq!(eth_index, 0.into());
-
- let eth_index = config.feed_index(make_feed_id("778680")); //eth
- assert_eq!(eth_index, None);
-
- let btc_index = config.feed_index(make_feed_id(BTC));
- assert_eq!(btc_index, 1.into());
-
- let avax_index = config.feed_index(make_feed_id(AVAX));
- assert_eq!(avax_index, None);
- }
-
- #[test]
- fn test_signer_index() {
- let config = Config::test();
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.into()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.to_uppercase()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.into()));
- assert_eq!(index, 1.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.replace('0', "1")));
- assert_eq!(index, None);
- }
-
- #[test]
- fn test_validate_timestamp() {
- let config = Config::test();
-
- config.validate_timestamp(0, TEST_BLOCK_TIMESTAMP);
- config.validate_timestamp(1, TEST_BLOCK_TIMESTAMP + 60000);
- config.validate_timestamp(2, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS);
- config.validate_timestamp(3, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS);
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP - 60000);
- }
-
- #[should_panic(expected = "Timestamp 2000000180001 is too future for #0")]
- #[test]
- fn test_validate_timestamp_too_future() {
- Config::test().validate_timestamp(0, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS + 1);
- }
-
- #[should_panic(expected = "Timestamp 1999999099999 is too old for #1")]
- #[test]
- fn test_validate_timestamp_too_old() {
- Config::test().validate_timestamp(1, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS - 1);
- }
-
- #[should_panic(expected = "Timestamp 0 is too old for #2")]
- #[test]
- fn test_validate_timestamp_zero() {
- Config::test().validate_timestamp(2, 0);
- }
-
- #[should_panic(expected = "Timestamp 4000000000000 is too future for #3")]
- #[test]
- fn test_validate_timestamp_big() {
- Config::test().validate_timestamp(3, TEST_BLOCK_TIMESTAMP + TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Timestamp 2000000000000 is too future for #4")]
- #[test]
- fn test_validate_timestamp_no_block_timestamp() {
- let mut config = Config::test();
-
- config.block_timestamp = 0;
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #0 (ETH)")]
- #[test]
- fn test_validate_signer_count_threshold_empty_list() {
- Config::test().validate_signer_count_threshold(0, vec![].as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_shorter_list() {
- Config::test().validate_signer_count_threshold(1, vec![1u8].iter_into_opt().as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_list_with_nones() {
- Config::test().validate_signer_count_threshold(
- 1,
- vec![None, 1u8.into(), None].opt_iter_into_opt().as_slice(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_size() {
- validate_with_all_permutations(vec![1u8, 2].iter_into_opt(), vec![1u8, 2].iter_into());
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_signer_count() {
- validate_with_all_permutations(
- vec![None, 1u8.into(), None, 2.into()].opt_iter_into_opt(),
- vec![1u8, 2].iter_into(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_larger_size() {
- validate_with_all_permutations(
- vec![
- 1u8.into(),
- None,
- None,
- 2.into(),
- 3.into(),
- None,
- 4.into(),
- None,
- ]
- .opt_iter_into_opt(),
- vec![1u8, 2, 3, 4].iter_into(),
- );
- }
-
- fn validate_with_all_permutations(numbers: Vec<Option<U256>>, expected_value: Vec<U256>) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
- let mut config = Config::test();
-
- let result = config.validate_signer_count_threshold(0, &numbers);
- assert_eq!(result, expected_value);
-
- for threshold in 0..expected_value.len() + 1 {
- config.signer_count_threshold = threshold as u8;
-
- for (index, perm) in perms.iter().enumerate() {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- let result =
- config.validate_signer_count_threshold(index % config.feed_ids.len(), &p);
- assert_eq!(result.len(), expected_value.len());
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -
use sha3::{Digest, Keccak256};
-
-pub fn keccak256(data: &[u8]) -> Box<[u8]> {
- Keccak256::new_with_prefix(data)
- .finalize()
- .as_slice()
- .into()
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{crypto::keccak256::keccak256, helpers::hex::hex_to_bytes};
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const EMPTY_MESSAGE_HASH: &str =
- "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
-
- #[test]
- fn test_keccak256() {
- let hash = keccak256(hex_to_bytes(MESSAGE.into()).as_slice());
-
- assert_eq!(hash.as_ref(), hex_to_bytes(MESSAGE_HASH.into()).as_slice());
- }
-
- #[test]
- fn test_keccak256_empty() {
- let hash = keccak256(vec![].as_slice());
-
- assert_eq!(
- hash.as_ref(),
- hex_to_bytes(EMPTY_MESSAGE_HASH.into()).as_slice()
- );
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -
use crate::crypto::{keccak256, recover::crypto256::recover_public_key};
-
-pub fn recover_address(message: Vec<u8>, signature: Vec<u8>) -> Vec<u8> {
- let recovery_byte = signature[64]; // 65-byte representation
- let msg_hash = keccak256::keccak256(message.as_slice());
- let key = recover_public_key(
- msg_hash,
- &signature[..64],
- recovery_byte - (if recovery_byte >= 27 { 27 } else { 0 }),
- );
- let key_hash = keccak256::keccak256(&key[1..]); // skip first uncompressed-key byte
-
- key_hash[12..].into() // last 20 bytes
-}
-
-#[cfg(feature = "crypto_secp256k1")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use secp256k1::{ecdsa::RecoverableSignature, Message, Secp256k1 as Secp256k1Curve};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let msg = Message::from_digest_slice(message_hash.as_ref())
- .unwrap_or_revert(|_| Error::CryptographicError(message_hash.len()));
-
- let recovery_id = secp256k1::ecdsa::RecoveryId::from_i32(recovery_byte.into())
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let sig: RecoverableSignature =
- RecoverableSignature::from_compact(signature_bytes, recovery_id)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let public_key = Secp256k1Curve::new().recover_ecdsa(&msg, &sig);
-
- public_key.unwrap().serialize_uncompressed().into()
- }
-}
-
-#[cfg(feature = "crypto_k256")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let recovery_id = RecoveryId::from_byte(recovery_byte)
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let signature = Signature::try_from(signature_bytes)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let recovered_key =
- VerifyingKey::recover_from_prehash(message_hash.as_ref(), &signature, recovery_id)
- .map(|key| key.to_encoded_point(false).to_bytes());
-
- recovered_key.unwrap()
- }
-}
-
-#[cfg(all(not(feature = "crypto_k256"), not(feature = "crypto_secp256k1")))]
-pub(crate) mod crypto256 {
- pub(crate) fn recover_public_key(
- _message_hash: Box<[u8]>,
- _signature_bytes: &[u8],
- _recovery_byte: u8,
- ) -> Box<[u8]> {
- panic!("Not implemented!")
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- crypto::recover::{crypto256::recover_public_key, recover_address},
- helpers::hex::hex_to_bytes,
- };
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const SIG_V27: &str = "475195641dae43318e194c3d9e5fc308773d6fdf5e197e02644dfd9ca3d19e3e2bd7d8656428f7f02e658a16b8f83722169c57126cc50bec8fad188b1bac6d19";
- const SIG_V28: &str = "c88242d22d88252c845b946c9957dbf3c7d59a3b69ecba2898198869f9f146ff268c3e47a11dbb05cc5198aadd659881817a59ee37e088d3253f4695927428c1";
- const PUBLIC_KEY_V27: &str =
- "04f5f035588502146774d0ccfd62ee5bf1d7f1dbb96aae33a79765c636b8ec75a36f5121931b5cc37215a7d4280c5700ca92daaaf93c32b06ca9f98b1f4ece624e";
- const PUBLIC_KEY_V28: &str =
- "04626f2ad2cfb0b41a24276d78de8959bcf45fc5e80804416e660aab2089d15e98206526e639ee19d17c8f9ae0ce3a6ff1a8ea4ab773d0fb4214e08aad7ba978c8";
- const ADDRESS_V27: &str = "2c59617248994D12816EE1Fa77CE0a64eEB456BF";
- const ADDRESS_V28: &str = "12470f7aBA85c8b81D63137DD5925D6EE114952b";
-
- #[test]
- fn test_recover_public_key_v27() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V27), 0);
-
- assert_eq!(u8_box(PUBLIC_KEY_V27), public_key);
- }
-
- #[test]
- fn test_recover_public_key_v28() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V28), 1);
-
- assert_eq!(u8_box(PUBLIC_KEY_V28), public_key);
- }
-
- #[test]
- fn test_recover_address_1b() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V27.to_owned() + "1b"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V27.into()), address);
- }
-
- #[test]
- fn test_recover_address_1c() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V28.to_owned() + "1c"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V28.into()), address);
- }
-
- fn u8_box(str: &str) -> Box<[u8]> {
- hex_to_bytes(str.into()).as_slice().into()
- }
-}
-
//! # RedStone
-//!
-//! `redstone` is a collection of utilities to make deserializing&decrypting RedStone payload.
-//! It includes a pure Rust implementation, along with extensions for certain networks.
-//!
-//! Different crypto-mechanisms are easily injectable.
-//! The current implementation contains `secp256k1`- and `k256`-based variants.
-
-pub mod core;
-mod crypto;
-pub mod network;
-mod protocol;
-mod utils;
-
-#[cfg(feature = "helpers")]
-pub mod helpers;
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -
extern crate alloc;
-
-use crate::network::specific::U256;
-use alloc::{format, string::String};
-
-pub trait AsHexStr {
- fn as_hex_str(&self) -> String;
-}
-
-impl AsHexStr for &[u8] {
- #[allow(clippy::format_collect)]
- fn as_hex_str(&self) -> String {
- self.iter().map(|byte| format!("{:02x}", byte)).collect()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsHexStr for casper_types::bytesrepr::Bytes {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- format!("{:X}", self)
- }
-}
-
-#[cfg(feature = "network_radix")]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- let digits = self.to_digits();
- let mut result = String::new();
- for &part in &digits {
- if result.is_empty() || part != 0u64 {
- result.push_str(&format!("{:02X}", part));
- }
- }
- result
- }
-}
-
-impl AsHexStr for Vec<u8> {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-impl AsHexStr for Box<[u8]> {
- fn as_hex_str(&self) -> String {
- self.as_ref().as_hex_str()
- }
-}
-
-pub trait AsAsciiStr {
- fn as_ascii_str(&self) -> String;
-}
-
-impl AsAsciiStr for &[u8] {
- fn as_ascii_str(&self) -> String {
- self.iter().map(|&code| code as char).collect()
- }
-}
-
-impl AsAsciiStr for Vec<u8> {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsAsciiStr for casper_types::bytesrepr::Bytes {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-impl AsAsciiStr for U256 {
- fn as_ascii_str(&self) -> String {
- let hex_string = self.as_hex_str();
- let bytes = (0..hex_string.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&hex_string[i..i + 2], 16))
- .collect::<Result<Vec<u8>, _>>()
- .unwrap();
-
- bytes.as_ascii_str()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
- };
-
- const ETH: u32 = 4543560u32;
-
- #[test]
- fn test_as_hex_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_hex_str();
-
- assert_eq!(result, "455448");
- }
-
- #[test]
- fn test_as_ascii_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_ascii_str();
-
- assert_eq!(result, "ETH");
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -
use crate::{
- network::{error::Error, specific::revert},
- print_debug,
-};
-use std::fmt::Debug;
-
-pub trait Assert<F> {
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
-
-impl<T, F> Assert<F> for T
-where
- T: Debug,
- F: Fn(&Self) -> bool,
-{
- fn assert_or_revert<E: FnOnce(&Self) -> Error>(self, check: F, error: E) -> Self {
- assert_or_revert(self, check, error)
- }
-}
-
-#[inline]
-fn assert_or_revert<F, T, E: FnOnce(&T) -> Error>(arg: T, check: F, error: E) -> T
-where
- F: Fn(&T) -> bool,
- T: Debug,
-{
- assert_or_revert_bool_with(check(&arg), || error(&arg));
-
- arg
-}
-
-#[inline]
-fn assert_or_revert_bool_with<E: FnOnce() -> Error>(check: bool, error: E) {
- if check {
- return;
- }
-
- let error = error();
- print_debug!("REVERT({}) - {}!", &error.code(), error);
- revert(error);
-}
-
-pub trait Unwrap<R> {
- type ErrorArg;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
-
-impl<T> Unwrap<T> for Option<T>
-where
- T: Debug,
-{
- type ErrorArg = ();
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(self, |arg| arg.is_some(), |_| error(&())).unwrap()
- }
-}
-
-impl<T, Err> Unwrap<T> for Result<T, Err>
-where
- T: Debug,
- Err: Debug,
-{
- type ErrorArg = Err;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(
- self,
- |arg| arg.is_ok(),
- |e| error(e.as_ref().err().unwrap()),
- )
- .unwrap()
- }
-}
-
-#[cfg(test)]
-mod assert_or_revert_tests {
- use crate::network::{
- assert::{assert_or_revert_bool_with, Assert},
- error::Error,
- };
-
- #[test]
- fn test_assert_or_revert_bool_with_true() {
- assert_or_revert_bool_with(true, || Error::ArrayIsEmpty);
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_assert_or_revert_bool_with_false() {
- assert_or_revert_bool_with(false, || Error::ArrayIsEmpty);
- }
-
- #[test]
- fn test_assert_or_revert_correct() {
- 5.assert_or_revert(|&x| x == 5, |&size| Error::SizeNotSupported(size));
- }
-
- #[should_panic(expected = "Size not supported: 5")]
- #[test]
- fn test_assert_or_revert_wrong() {
- 5.assert_or_revert(|&x| x < 5, |&size| Error::SizeNotSupported(size));
- }
-}
-
-#[cfg(test)]
-mod unwrap_or_revert_tests {
- use crate::network::{assert::Unwrap, error::Error};
-
- #[test]
- fn test_unwrap_or_revert_some() {
- let result = Some(543).unwrap_or_revert(|_| Error::CryptographicError(333));
-
- assert_eq!(result, 543);
- }
-
- #[should_panic(expected = "Cryptographic Error: 333")]
- #[test]
- fn test_unwrap_or_revert_none() {
- (Option::<u64>::None).unwrap_or_revert(|_| Error::CryptographicError(333));
- }
-
- #[test]
- fn test_unwrap_or_revert_ok() {
- let result = Ok(256).unwrap_or_revert(|_: &Error| Error::CryptographicError(333));
-
- assert_eq!(result, 256);
- }
-
- #[should_panic(expected = "Cryptographic Error: 567")]
- #[test]
- fn test_unwrap_or_revert_err() {
- Result::<&[u8], Error>::Err(Error::CryptographicError(567)).unwrap_or_revert(|e| e.clone());
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod error;
-mod from_bytes_repr;
-
-pub struct Casper;
-
-impl NetworkSpecific for Casper {
- type BytesRepr = casper_types::bytesrepr::Bytes;
- type ValueRepr = casper_types::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- casper_contract::contract_api::runtime::print(&_text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- casper_contract::contract_api::runtime::revert(error)
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -
use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
-};
-use std::fmt::{Debug, Display, Formatter};
-
-pub trait ContractErrorContent: Debug {
- fn code(&self) -> u8;
- fn message(&self) -> String;
-}
-
-/// Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-///
-/// These errors include issues with contract logic, data types,
-/// cryptographic operations, and conditions specific to the requirements.
-#[derive(Debug)]
-pub enum Error {
- /// Represents errors that arise from the contract itself.
- ///
- /// This variant is used for encapsulating errors that are specific to the contract's logic
- /// or execution conditions that aren't covered by more specific error types.
- ContractError(Box<dyn ContractErrorContent>),
-
- /// Indicates an overflow error with `U256` numbers.
- ///
- /// Used when operations on `U256` numbers exceed their maximum value, potentially leading
- /// to incorrect calculations or state.
- NumberOverflow(U256),
-
- /// Used when an expected non-empty array or vector is found to be empty.
- ///
- /// This could occur in scenarios where the contract logic requires a non-empty collection
- /// of items for the correct operation, for example, during aggregating the values.
- ArrayIsEmpty,
-
- /// Represents errors related to cryptographic operations.
- ///
- /// This includes failures in signature verification, hashing, or other cryptographic
- /// processes, with the usize indicating the position or identifier of the failed operation.
- CryptographicError(usize),
-
- /// Signifies that an unsupported size was encountered.
- ///
- /// This could be used when a data structure or input does not meet the expected size
- /// requirements for processing.
- SizeNotSupported(usize),
-
- /// Indicates that the marker bytes for RedStone are incorrect.
- ///
- /// This error is specific to scenarios where marker or identifier bytes do not match
- /// expected values, potentially indicating corrupted or tampered data.
- WrongRedStoneMarker(Vec<u8>),
-
- /// Used when there is leftover data in a payload that should have been empty.
- ///
- /// This could indicate an error in data parsing or that additional, unexpected data
- /// was included in a message or transaction.
- NonEmptyPayloadRemainder(Vec<u8>),
-
- /// Indicates that the number of signers does not meet the required threshold.
- ///
- /// This variant includes the current number of signers, the required threshold, and
- /// potentially a feed_id related to the operation that failed due to insufficient signers.
- InsufficientSignerCount(usize, usize, U256),
-
- /// Used when a timestamp is older than allowed by the processor logic.
- ///
- /// Includes the position or identifier of the timestamp and the threshold value,
- /// indicating that the provided timestamp is too far in the past.
- TimestampTooOld(usize, u64),
-
- /// Indicates that a timestamp is further in the future than allowed.
- ///
- /// Similar to `TimestampTooOld`, but for future timestamps exceeding the contract's
- /// acceptance window.
- TimestampTooFuture(usize, u64),
-
- /// Represents errors that need to clone `ContractErrorContent`, which is not supported by default.
- ///
- /// This variant allows for the manual duplication of contract error information, including
- /// an error code and a descriptive message.
- ClonedContractError(u8, String),
-}
-
-impl Error {
- pub fn contract_error<T: ContractErrorContent + 'static>(value: T) -> Error {
- Error::ContractError(Box::new(value))
- }
-
- pub(crate) fn code(&self) -> u16 {
- match self {
- Error::ContractError(boxed) => boxed.code() as u16,
- Error::NumberOverflow(_) => 509,
- Error::ArrayIsEmpty => 510,
- Error::WrongRedStoneMarker(_) => 511,
- Error::NonEmptyPayloadRemainder(_) => 512,
- Error::InsufficientSignerCount(data_package_index, value, _) => {
- (2000 + data_package_index * 10 + value) as u16
- }
- Error::SizeNotSupported(size) => 600 + *size as u16,
- Error::CryptographicError(size) => 700 + *size as u16,
- Error::TimestampTooOld(data_package_index, _) => 1000 + *data_package_index as u16,
- Error::TimestampTooFuture(data_package_index, _) => 1050 + *data_package_index as u16,
- Error::ClonedContractError(code, _) => *code as u16,
- }
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- Error::ContractError(boxed) => write!(f, "Contract error: {}", boxed.message()),
- Error::NumberOverflow(number) => write!(f, "Number overflow: {}", number),
- Error::ArrayIsEmpty => write!(f, "Array is empty"),
- Error::CryptographicError(size) => write!(f, "Cryptographic Error: {}", size),
- Error::SizeNotSupported(size) => write!(f, "Size not supported: {}", size),
- Error::WrongRedStoneMarker(bytes) => {
- write!(f, "Wrong RedStone marker: {}", bytes.as_hex_str())
- }
- Error::NonEmptyPayloadRemainder(bytes) => {
- write!(f, "Non empty payload remainder: {}", bytes.as_hex_str())
- }
- Error::InsufficientSignerCount(data_package_index, value, feed_id) => write!(
- f,
- "Insufficient signer count {} for #{} ({})",
- value,
- data_package_index,
- feed_id.as_ascii_str()
- ),
- Error::TimestampTooOld(data_package_index, value) => {
- write!(
- f,
- "Timestamp {} is too old for #{}",
- value, data_package_index
- )
- }
- Error::TimestampTooFuture(data_package_index, value) => write!(
- f,
- "Timestamp {} is too future for #{}",
- value, data_package_index
- ),
- Error::ClonedContractError(_, message) => {
- write!(f, "(Cloned) Contract error: {}", message)
- }
- }
- }
-}
-
-impl Clone for Error {
- fn clone(&self) -> Self {
- match self {
- Error::ContractError(content) => {
- Error::ClonedContractError(content.code(), content.message())
- }
- Error::NumberOverflow(value) => Error::NumberOverflow(*value),
- Error::ArrayIsEmpty => Error::ArrayIsEmpty,
- Error::CryptographicError(size) => Error::CryptographicError(*size),
- Error::SizeNotSupported(size) => Error::SizeNotSupported(*size),
- Error::WrongRedStoneMarker(bytes) => Error::WrongRedStoneMarker(bytes.clone()),
- Error::NonEmptyPayloadRemainder(bytes) => {
- Error::NonEmptyPayloadRemainder(bytes.clone())
- }
- Error::InsufficientSignerCount(count, needed, bytes) => {
- Error::InsufficientSignerCount(*count, *needed, *bytes)
- }
- Error::TimestampTooOld(index, timestamp) => Error::TimestampTooOld(*index, *timestamp),
- Error::TimestampTooFuture(index, timestamp) => {
- Error::TimestampTooFuture(*index, *timestamp)
- }
- Error::ClonedContractError(code, message) => {
- Error::ClonedContractError(*code, message.as_str().into())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -
use crate::network::specific::Bytes;
-
-pub trait Flattened<T> {
- fn flattened(&self) -> T;
-}
-
-impl Flattened<Bytes> for Vec<Bytes> {
- fn flattened(&self) -> Bytes {
- #[allow(clippy::useless_conversion)]
- self.iter().flatten().copied().collect::<Vec<_>>().into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{flattened::Flattened, specific::Bytes};
-
- #[test]
- fn test_bytes_flattened() {
- #[allow(clippy::useless_conversion)]
- let bytes: Vec<Bytes> = vec![
- vec![1u8, 2, 3].into(),
- vec![4u8].into(),
- vec![].into(),
- vec![5, 6, 7].into(),
- ];
-
- let result: Bytes = bytes.flattened();
-
- #[allow(clippy::useless_conversion)]
- let expected_result: Bytes = vec![1u8, 2, 3, 4, 5, 6, 7].into();
-
- assert_eq!(result, expected_result);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -
use crate::network::specific::VALUE_SIZE;
-
-pub trait FromBytesRepr<T> {
- fn from_bytes_repr(bytes: T) -> Self;
-}
-
-pub trait Sanitized {
- fn sanitized(self) -> Self;
-}
-
-impl Sanitized for Vec<u8> {
- fn sanitized(self) -> Self {
- if self.len() <= VALUE_SIZE {
- return self;
- }
-
- let index = self.len().max(VALUE_SIZE) - VALUE_SIZE;
- let remainder = &self[0..index];
-
- if remainder != vec![0; index] {
- panic!("Number to big: {:?} digits", self.len())
- }
-
- self[index..].into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- };
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[test]
- fn test_from_bytes_repr_single() {
- let vec = vec![1];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(1u32));
- }
-
- #[test]
- fn test_from_bytes_repr_double() {
- let vec = vec![1, 2];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(258u32));
- }
-
- #[test]
- fn test_from_bytes_repr_simple() {
- let vec = vec![1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[test]
- fn test_from_bytes_repr_bigger() {
- let vec = vec![101, 202, 255];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(6671103u32));
- }
-
- #[test]
- fn test_from_bytes_repr_empty() {
- let result = U256::from_bytes_repr(Vec::new());
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[test]
- fn test_from_bytes_repr_trailing_zeroes() {
- let vec = vec![1, 2, 3, 0];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(16909056u32));
- }
-
- #[test]
- fn test_from_bytes_repr_leading_zeroes() {
- let vec = vec![0, 1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_max() {
- let vec = vec![255; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-
- #[test]
- fn test_from_bytes_repr_min() {
- let vec = vec![0; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[should_panic(expected = "Number to big")]
- #[test]
- fn test_from_bytes_repr_too_long() {
- let x = VALUE_SIZE as u8 + 1;
- let vec = (1..=x).collect();
-
- U256::from_bytes_repr(vec);
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_too_long_but_zeroes() {
- let mut vec = vec![255; VALUE_SIZE + 1];
- vec[0] = 0;
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-}
-
pub mod as_str;
-pub mod assert;
-pub mod error;
-pub mod from_bytes_repr;
-pub mod print_debug;
-pub mod specific;
-
-#[cfg(feature = "network_casper")]
-pub mod casper;
-
-#[cfg(feature = "network_casper")]
-pub type _Network = casper::Casper;
-
-#[cfg(feature = "network_radix")]
-pub mod radix;
-
-#[cfg(feature = "network_radix")]
-pub type _Network = radix::Radix;
-
-pub mod flattened;
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-mod pure;
-
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-pub type _Network = pure::Std;
-
extern crate alloc;
-
-#[macro_export]
-macro_rules! print_debug {
- ($fmt:expr) => {
- $crate::network::specific::print(format!($fmt))
- };
- ($fmt:expr, $($args:tt)*) => {
- $crate::network::specific::print(format!($fmt, $($args)*))
- };
-}
-
-#[macro_export]
-macro_rules! print_and_panic {
- ($fmt:expr) => {{
- $crate::print_debug!($fmt);
- panic!($fmt)
- }};
- ($fmt:expr, $($args:tt)*) => {{
- $crate::print_debug!($fmt, $($args)*);
- panic!($fmt, $($args)*)
- }};
-}
-
use crate::network::{error::Error, specific::NetworkSpecific};
-use primitive_types::U256;
-use std::eprintln;
-
-mod from_bytes_repr;
-
-pub struct Std;
-
-impl NetworkSpecific for Std {
- type BytesRepr = Vec<u8>;
- type ValueRepr = U256;
- type _Self = Std;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(text: String) {
- eprintln!("{}", text)
- }
-
- fn revert(error: Error) -> ! {
- panic!("{}", error)
- }
-}
-
use crate::network::{
- from_bytes_repr::{FromBytesRepr, Sanitized},
- specific::U256,
-};
-
-impl FromBytesRepr<Vec<u8>> for U256 {
- fn from_bytes_repr(bytes: Vec<u8>) -> Self {
- match bytes.len() {
- 0 => U256::ZERO,
- 1 => U256::from(bytes[0]),
- _ => {
- // TODO: make it cheaper
- let mut bytes_le = bytes.sanitized();
- bytes_le.reverse();
-
- U256::from_le_bytes(bytes_le.as_slice())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod from_bytes_repr;
-pub mod u256_ext;
-
-pub struct Radix;
-
-impl NetworkSpecific for Radix {
- type BytesRepr = Vec<u8>;
- type ValueRepr = radix_common::math::bnum_integer::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- scrypto::prelude::info!("{}", _text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- scrypto::prelude::Runtime::panic(error.to_string())
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
use crate::network::{_Network, error::Error, from_bytes_repr::FromBytesRepr};
-
-pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
-
-pub(crate) type Network = <_Network as NetworkSpecific>::_Self;
-pub type Bytes = <_Network as NetworkSpecific>::BytesRepr;
-pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
-pub const VALUE_SIZE: usize = <_Network as NetworkSpecific>::VALUE_SIZE;
-
-pub fn print(_text: String) {
- Network::print(_text)
-}
-
-pub fn revert(error: Error) -> ! {
- Network::revert(error)
-}
-
pub(crate) const UNSIGNED_METADATA_BYTE_SIZE_BS: usize = 3;
-pub(crate) const DATA_PACKAGES_COUNT_BS: usize = 2;
-pub(crate) const DATA_POINTS_COUNT_BS: usize = 3;
-pub(crate) const SIGNATURE_BS: usize = 65;
-pub(crate) const DATA_POINT_VALUE_BYTE_SIZE_BS: usize = 4;
-pub(crate) const DATA_FEED_ID_BS: usize = 32;
-pub(crate) const TIMESTAMP_BS: usize = 6;
-pub(crate) const MAX_TIMESTAMP_DELAY_MS: u64 = 15 * 60 * 1000; // 15 minutes in milliseconds
-pub(crate) const MAX_TIMESTAMP_AHEAD_MS: u64 = 3 * 60 * 1000; // 3 minutes in milliseconds
-pub(crate) const REDSTONE_MARKER_BS: usize = 9;
-pub(crate) const REDSTONE_MARKER: [u8; 9] = [0, 0, 2, 237, 87, 1, 30, 0, 0]; // 0x000002ed57011e0000
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -
use crate::{
- crypto::recover::recover_address,
- network::as_str::AsHexStr,
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_point::{trim_data_points, DataPoint},
- },
- utils::trim::Trim,
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
-
-pub(crate) fn trim_data_packages(payload: &mut Vec<u8>, count: usize) -> Vec<DataPackage> {
- let mut data_packages = Vec::new();
-
- for _ in 0..count {
- let data_package = trim_data_package(payload);
- data_packages.push(data_package);
- }
-
- data_packages
-}
-
-fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage {
- let signature = payload.trim_end(SIGNATURE_BS);
- let mut tmp = payload.clone();
-
- let data_point_count = payload.trim_end(DATA_POINTS_COUNT_BS);
- let value_size = payload.trim_end(DATA_POINT_VALUE_BYTE_SIZE_BS);
- let timestamp = payload.trim_end(TIMESTAMP_BS);
- let size = data_point_count * (value_size + DATA_FEED_ID_BS)
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + DATA_POINTS_COUNT_BS;
-
- let signable_bytes = tmp.trim_end(size);
- let signer_address = recover_address(signable_bytes, signature);
-
- let data_points = trim_data_points(payload, data_point_count, value_size);
-
- DataPackage {
- data_points,
- timestamp,
- signer_address,
- }
-}
-
-impl Debug for DataPackage {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPackage {{\n signer_address: 0x{}, timestamp: {},\n data_points: {:?}\n}}",
- self.signer_address.as_hex_str(),
- self.timestamp,
- self.data_points
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{from_bytes_repr::FromBytesRepr, specific::U256},
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_package::{trim_data_package, trim_data_packages, DataPackage},
- data_point::DataPoint,
- },
- };
-
- const DATA_PACKAGE_BYTES_1: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e018d79bf0ba00000002000000151afa8c5c3caf6004b42c0fb17723e524f993b9ecbad3b9bce5ec74930fa436a3660e8edef10e96ee5f222de7ef5787c02ca467c0ec18daa2907b43ac20c63c11c";
- const DATA_PACKAGE_BYTES_2: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cdd851e018d79bf0ba000000020000001473fd9dc72e6814a7de719b403cf4c9eba08934a643fd0666c433b806b31e69904f2226ffd3c8ef75861b11b5e32a1fda4b1458e0da4605a772dfba2a812f3ee1b";
-
- const SIGNER_ADDRESS_1: &str = "1ea62d73edf8ac05dfcea1a34b9796e937a29eff";
- const SIGNER_ADDRESS_2: &str = "109b4a318a4f5ddcbca6349b45f881b4137deafb";
-
- const VALUE_1: u128 = 232141080910;
- const VALUE_2: u128 = 232144078110;
-
- const DATA_PACKAGE_SIZE: usize = 32
- + DATA_FEED_ID_BS
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + SIGNATURE_BS
- + DATA_POINTS_COUNT_BS;
-
- #[test]
- fn test_trim_data_packages() {
- test_trim_data_packages_of(2, "");
- test_trim_data_packages_of(0, "");
- test_trim_data_packages_of(1, "");
- }
-
- #[test]
- fn test_trim_data_packages_with_prefix() {
- let prefix = "da4687f1914a1c";
-
- test_trim_data_packages_of(2, prefix);
- }
-
- #[test]
- fn test_trim_data_packages_single() {
- let mut bytes = hex_to_bytes(DATA_PACKAGE_BYTES_1.into());
- let data_packages = trim_data_packages(&mut bytes, 1);
- assert_eq!(data_packages.len(), 1);
- assert_eq!(bytes, Vec::<u8>::new());
-
- verify_data_package(data_packages[0].clone(), VALUE_1, SIGNER_ADDRESS_1);
- }
-
- fn test_trim_data_packages_of(count: usize, prefix: &str) {
- let input: Vec<u8> =
- hex_to_bytes((prefix.to_owned() + DATA_PACKAGE_BYTES_1) + DATA_PACKAGE_BYTES_2);
- let mut bytes = input.clone();
- let data_packages = trim_data_packages(&mut bytes, count);
-
- assert_eq!(data_packages.len(), count);
- assert_eq!(
- bytes.as_slice(),
- &input[..input.len() - count * DATA_PACKAGE_SIZE]
- );
-
- let values = &[VALUE_2, VALUE_1];
- let signers = &[SIGNER_ADDRESS_2, SIGNER_ADDRESS_1];
-
- for i in 0..count {
- verify_data_package(data_packages[i].clone(), values[i], signers[i]);
- }
- }
-
- #[should_panic(expected = "index out of bounds")]
- #[test]
- fn test_trim_data_packages_bigger_number() {
- test_trim_data_packages_of(3, "");
- }
-
- #[test]
- fn test_trim_data_package() {
- test_trim_data_package_of(DATA_PACKAGE_BYTES_1, VALUE_1, SIGNER_ADDRESS_1);
- test_trim_data_package_of(DATA_PACKAGE_BYTES_2, VALUE_2, SIGNER_ADDRESS_2);
- }
-
- #[test]
- fn test_trim_data_package_with_prefix() {
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_1),
- VALUE_1,
- SIGNER_ADDRESS_1,
- );
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_2),
- VALUE_2,
- SIGNER_ADDRESS_2,
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_signature_only() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1[(DATA_PACKAGE_BYTES_1.len() - 2 * SIGNATURE_BS)..],
- 0,
- "",
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_shorter() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1
- [(DATA_PACKAGE_BYTES_1.len() - 2 * (SIGNATURE_BS + DATA_POINTS_COUNT_BS))..],
- 0,
- "",
- );
- }
-
- fn test_trim_data_package_of(bytes_str: &str, expected_value: u128, signer_address: &str) {
- let mut bytes: Vec<u8> = hex_to_bytes(bytes_str.into());
- let result = trim_data_package(&mut bytes);
- assert_eq!(
- bytes,
- hex_to_bytes(bytes_str[..bytes_str.len() - 2 * (DATA_PACKAGE_SIZE)].into())
- );
-
- verify_data_package(result, expected_value, signer_address);
- }
-
- fn verify_data_package(result: DataPackage, expected_value: u128, signer_address: &str) {
- let data_package = DataPackage {
- data_points: vec![DataPoint {
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_PACKAGE_BYTES_1[..6].into())),
- value: U256::from(expected_value),
- }],
- timestamp: 1707144580000,
- signer_address: hex_to_bytes(signer_address.into()),
- };
-
- assert_eq!(result, data_package);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -
use crate::{
- network::{
- as_str::{AsAsciiStr, AsHexStr},
- assert::Assert,
- error::Error,
- from_bytes_repr::FromBytesRepr,
- specific::U256,
- },
- protocol::constants::DATA_FEED_ID_BS,
- utils::{trim::Trim, trim_zeros::TrimZeros},
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
-
-pub(crate) fn trim_data_points(
- payload: &mut Vec<u8>,
- count: usize,
- value_size: usize,
-) -> Vec<DataPoint> {
- count.assert_or_revert(|&count| count == 1, |&count| Error::SizeNotSupported(count));
-
- let mut data_points = Vec::new();
-
- for _ in 0..count {
- let data_point = trim_data_point(payload, value_size);
- data_points.push(data_point);
- }
-
- data_points
-}
-
-fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint {
- let value = payload.trim_end(value_size);
- let feed_id: Vec<u8> = payload.trim_end(DATA_FEED_ID_BS);
-
- DataPoint {
- value,
- feed_id: U256::from_bytes_repr(feed_id.trim_zeros()),
- }
-}
-
-impl Debug for DataPoint {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPoint {{\n feed_id: {:?} (0x{}), value: {}\n }}",
- self.feed_id.as_ascii_str(),
- self.feed_id.as_hex_str(),
- self.value,
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- },
- protocol::{
- constants::DATA_FEED_ID_BS,
- data_point::{trim_data_point, trim_data_points, DataPoint},
- },
- };
- use std::ops::Shr;
-
- const DATA_POINT_BYTES_TAIL: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e";
- const VALUE: u128 = 232141080910;
-
- #[test]
- fn test_trim_data_points() {
- let mut bytes = hex_to_bytes(DATA_POINT_BYTES_TAIL.into());
- let result = trim_data_points(&mut bytes, 1, 32);
-
- assert_eq!(result.len(), 1);
-
- verify_rest_and_result(
- DATA_POINT_BYTES_TAIL,
- 32,
- VALUE.into(),
- bytes,
- result[0].clone(),
- )
- }
-
- #[should_panic(expected = "Size not supported: 0")]
- #[test]
- fn test_trim_zero_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 0, 32);
- }
-
- #[should_panic(expected = "Size not supported: 2")]
- #[test]
- fn test_trim_two_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 2, 32);
- }
-
- #[test]
- fn test_trim_data_point() {
- test_trim_data_point_of(DATA_POINT_BYTES_TAIL, 32, VALUE.into());
- }
-
- #[test]
- fn test_trim_data_point_with_prefix() {
- test_trim_data_point_of(
- &("a2a812f3ee1b".to_owned() + DATA_POINT_BYTES_TAIL),
- 32,
- VALUE.into(),
- );
- }
-
- #[test]
- fn test_trim_data_point_other_lengths() {
- for i in 1..VALUE_SIZE {
- test_trim_data_point_of(
- &DATA_POINT_BYTES_TAIL[..DATA_POINT_BYTES_TAIL.len() - 2 * i],
- 32 - i,
- U256::from(VALUE).shr(8 * i as u32),
- );
- }
- }
-
- fn test_trim_data_point_of(value: &str, size: usize, expected_value: U256) {
- let mut bytes = hex_to_bytes(value.into());
- let result = trim_data_point(&mut bytes, size);
-
- verify_rest_and_result(value, size, expected_value, bytes, result);
- }
-
- fn verify_rest_and_result(
- value: &str,
- size: usize,
- expected_value: U256,
- rest: Vec<u8>,
- result: DataPoint,
- ) {
- assert_eq!(
- rest,
- hex_to_bytes(value[..value.len() - 2 * (size + DATA_FEED_ID_BS)].into())
- );
-
- let data_point = DataPoint {
- value: expected_value,
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_POINT_BYTES_TAIL[..6].to_string())),
- };
-
- assert_eq!(result, data_point);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
-};
-
-pub fn trim_redstone_marker(payload: &mut Vec<u8>) {
- let marker: Vec<u8> = payload.trim_end(REDSTONE_MARKER_BS);
-
- marker.as_slice().assert_or_revert(
- |&marker| marker == REDSTONE_MARKER,
- |&val| Error::WrongRedStoneMarker(val.into()),
- );
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- protocol::{constants::REDSTONE_MARKER_BS, marker::trim_redstone_marker},
- };
-
- const PAYLOAD_TAIL: &str = "1c000f000000000002ed57011e0000";
-
- #[test]
- fn test_trim_redstone_marker() {
- let mut bytes = hex_to_bytes(PAYLOAD_TAIL.into());
- trim_redstone_marker(&mut bytes);
-
- assert_eq!(
- bytes,
- hex_to_bytes(PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2 * REDSTONE_MARKER_BS].into())
- );
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 000002ed57022e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong() {
- trim_redstone_marker(&mut hex_to_bytes(PAYLOAD_TAIL.replace('1', "2")));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 00000002ed57011e00")]
- #[test]
- fn test_trim_redstone_marker_wrong_ending() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2].into(),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 100002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong_beginning() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL.replace("0000000", "1111111"),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 0002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_too_short() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[PAYLOAD_TAIL.len() - 2 * (REDSTONE_MARKER_BS - 1)..].into(),
- ));
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::{
- constants::{DATA_PACKAGES_COUNT_BS, UNSIGNED_METADATA_BYTE_SIZE_BS},
- data_package::{trim_data_packages, DataPackage},
- marker,
- },
- utils::trim::Trim,
-};
-
-#[derive(Clone, Debug)]
-pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
-
-impl Payload {
- pub(crate) fn make(payload_bytes: &mut Vec<u8>) -> Payload {
- marker::trim_redstone_marker(payload_bytes);
- let payload = trim_payload(payload_bytes);
-
- payload_bytes.assert_or_revert(
- |bytes| bytes.is_empty(),
- |bytes| Error::NonEmptyPayloadRemainder(bytes.as_slice().into()),
- );
-
- payload
- }
-}
-
-fn trim_payload(payload: &mut Vec<u8>) -> Payload {
- let data_package_count = trim_metadata(payload);
- let data_packages = trim_data_packages(payload, data_package_count);
-
- Payload { data_packages }
-}
-
-fn trim_metadata(payload: &mut Vec<u8>) -> usize {
- let unsigned_metadata_size = payload.trim_end(UNSIGNED_METADATA_BYTE_SIZE_BS);
- let _: Vec<u8> = payload.trim_end(unsigned_metadata_size);
-
- payload.trim_end(DATA_PACKAGES_COUNT_BS)
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::{hex_to_bytes, read_payload_bytes, read_payload_hex},
- protocol::{
- constants::REDSTONE_MARKER_BS,
- payload::{trim_metadata, trim_payload, Payload},
- },
- };
-
- const PAYLOAD_METADATA_BYTES: &str = "000f000000";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTE: &str = "000f55000001";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTES: &str = "000f11223344556677889900aabbccddeeff000010";
-
- #[test]
- fn test_trim_metadata() {
- let prefix = "9e0294371c";
-
- for &bytes_str in &[
- PAYLOAD_METADATA_BYTES,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTE,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTES,
- ] {
- let mut bytes = hex_to_bytes(prefix.to_owned() + bytes_str);
- let result = trim_metadata(&mut bytes);
-
- assert_eq!(bytes, hex_to_bytes(prefix.into()));
- assert_eq!(result, 15);
- }
- }
-
- #[test]
- fn test_trim_payload() {
- let payload_hex = read_payload_bytes("./sample-data/payload.hex");
-
- let mut bytes = payload_hex[..payload_hex.len() - REDSTONE_MARKER_BS].into();
- let payload = trim_payload(&mut bytes);
-
- assert_eq!(bytes, Vec::<u8>::new());
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[test]
- fn test_make_payload() {
- let mut payload_hex = read_payload_bytes("./sample-data/payload.hex");
- let payload = Payload::make(&mut payload_hex);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[should_panic(expected = "Non empty payload remainder: 12")]
- #[test]
- fn test_make_payload_with_prefix() {
- let payload_hex = read_payload_hex("./sample-data/payload.hex");
- let mut bytes = hex_to_bytes("12".to_owned() + &payload_hex);
- let payload = Payload::make(&mut bytes);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-}
-
pub(crate) trait FilterSome<Output> {
- fn filter_some(&self) -> Output;
-}
-
-impl<T: Copy> FilterSome<Vec<T>> for [Option<T>] {
- fn filter_some(&self) -> Vec<T> {
- self.iter().filter_map(|&opt| opt).collect()
- }
-}
-
-#[cfg(test)]
-mod filter_some_tests {
- use crate::utils::filter::FilterSome;
-
- #[test]
- fn test_filter_some() {
- let values = [None, Some(23u64), None, Some(12), Some(12), None, Some(23)];
-
- assert_eq!(values.filter_some(), vec![23, 12, 12, 23])
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -
use crate::network::{assert::Assert, error::Error::ArrayIsEmpty, specific::U256};
-use std::ops::{Add, Rem, Shr};
-
-pub(crate) trait Median {
- type Item;
-
- fn median(self) -> Self::Item;
-}
-
-trait Avg {
- fn avg(self, other: Self) -> Self;
-}
-
-trait Averageable:
- Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy
-{
-}
-
-impl Averageable for i32 {}
-
-#[cfg(feature = "network_radix")]
-impl Avg for U256 {
- fn avg(self, other: Self) -> Self {
- let one = 1u32;
- let two = U256::from(2u8);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl Averageable for U256 {}
-
-impl<T> Avg for T
-where
- T: Averageable,
-{
- fn avg(self, other: Self) -> Self {
- let one = T::from(1);
- let two = T::from(2);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-impl<T> Median for Vec<T>
-where
- T: Copy + Ord + Avg,
-{
- type Item = T;
-
- fn median(self) -> Self::Item {
- let len = self.len();
-
- match len.assert_or_revert(|x| *x > 0, |_| ArrayIsEmpty) {
- 1 => self[0],
- 2 => self[0].avg(self[1]),
- 3 => maybe_pick_median(self[0], self[1], self[2]).unwrap_or_else(|| {
- maybe_pick_median(self[1], self[0], self[2])
- .unwrap_or_else(|| maybe_pick_median(self[1], self[2], self[0]).unwrap())
- }),
- _ => {
- let mut values = self;
- values.sort();
-
- let mid = len / 2;
-
- if len % 2 == 0 {
- values[mid - 1].avg(values[mid])
- } else {
- values[mid]
- }
- }
- }
- }
-}
-
-#[inline]
-fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>
-where
- T: PartialOrd,
-{
- if (b >= a && b <= c) || (b >= c && b <= a) {
- Some(b)
- } else {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{Avg, Median};
- use crate::network::specific::U256;
- use itertools::Itertools;
- use std::fmt::Debug;
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_avg() {
- let u256 = U256::max_value(); // 115792089237316195423570985008687907853269984665640564039457584007913129639935
- let u256_max_sub_1 = u256 - U256::from(1u32);
- let u256max_div_2 = u256 / U256::from(2u32);
-
- assert_eq!(u256.avg(U256::from(0u8)), u256max_div_2);
- assert_eq!(u256.avg(U256::from(1u8)), u256max_div_2 + U256::from(1u8));
- assert_eq!(u256.avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!(u256.avg(u256), u256);
-
- assert_eq!((u256_max_sub_1).avg(U256::from(0u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(U256::from(1u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!((u256_max_sub_1).avg(u256), u256_max_sub_1);
- }
-
- #[test]
- #[should_panic(expected = "Array is empty")]
- fn test_median_empty_vector() {
- let vec: Vec<i32> = vec![];
-
- vec.median();
- }
-
- #[test]
- fn test_median_single_element() {
- assert_eq!(vec![1].median(), 1);
- }
-
- #[test]
- fn test_median_two_elements() {
- test_all_permutations(vec![1, 3], 2);
- test_all_permutations(vec![1, 2], 1);
- test_all_permutations(vec![1, 1], 1);
- }
-
- #[test]
- fn test_median_three_elements() {
- test_all_permutations(vec![1, 2, 3], 2);
- test_all_permutations(vec![1, 1, 2], 1);
- test_all_permutations(vec![1, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1], 1);
- }
-
- #[test]
- fn test_median_even_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4], 2);
- test_all_permutations(vec![1, 2, 4, 4], 3);
- test_all_permutations(vec![1, 1, 3, 3], 2);
- test_all_permutations(vec![1, 1, 3, 4], 2);
- test_all_permutations(vec![1, 1, 1, 3], 1);
- test_all_permutations(vec![1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 1, 1, 1], 1);
- test_all_permutations(vec![1, 2, 3, 4, 5, 6], 3);
- }
-
- #[test]
- fn test_median_odd_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 1, 4, 5], 1);
- test_all_permutations(vec![1, 1, 1, 3, 3], 1);
- test_all_permutations(vec![1, 1, 3, 3, 5], 3);
-
- test_all_permutations(vec![1, 2, 3, 5, 5], 3);
- test_all_permutations(vec![1, 2, 5, 5, 5], 5);
- test_all_permutations(vec![1, 1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 3, 3, 5, 5], 3);
-
- test_all_permutations(vec![1, 2, 2, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1, 1, 2], 1);
- test_all_permutations(vec![1, 1, 1, 1, 1], 1);
-
- test_all_permutations(vec![1, 2, 3, 4, 5, 6, 7], 4);
- }
-
- fn test_all_permutations<T: Copy + Ord + Avg + Debug>(numbers: Vec<T>, expected_value: T) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
-
- for perm in perms {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- assert_eq!(p.median(), expected_value);
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -
use crate::network::{
- assert::Unwrap, error::Error, from_bytes_repr::FromBytesRepr, specific::U256,
-};
-
-pub trait Trim<T>
-where
- Self: Sized,
-{
- fn trim_end(&mut self, len: usize) -> T;
-}
-
-impl Trim<Vec<u8>> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> Self {
- if len >= self.len() {
- std::mem::take(self)
- } else {
- self.split_off(self.len() - len)
- }
- }
-}
-
-impl Trim<U256> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> U256 {
- U256::from_bytes_repr(self.trim_end(len))
- }
-}
-
-impl Trim<usize> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> usize {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-impl Trim<u64> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> u64 {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{
- network::specific::U256,
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
- };
-
- const MARKER_DECIMAL: u64 = 823907890102272;
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.into()
- }
-
- #[test]
- fn test_trim_end_number() {
- let (rest, result): (_, U256) = test_trim_end(3);
- assert_eq!(result, (256u32.pow(2) * 30).into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER[..6]);
-
- let (_, result): (_, u64) = test_trim_end(3);
- assert_eq!(result, 256u64.pow(2) * 30);
-
- let (_, result): (_, usize) = test_trim_end(3);
- assert_eq!(result, 256usize.pow(2) * 30);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(3);
- assert_eq!(result.as_slice(), &REDSTONE_MARKER[6..]);
- }
-
- #[test]
- fn test_trim_end_number_null() {
- let (rest, result): (_, U256) = test_trim_end(0);
- assert_eq!(result, 0u32.into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER);
-
- let (_, result): (_, u64) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, usize) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(0);
- assert_eq!(result, Vec::<u8>::new());
- }
-
- #[test]
- fn test_trim_end_whole() {
- test_trim_end_whole_size(REDSTONE_MARKER_BS);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 1);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 2);
- test_trim_end_whole_size(REDSTONE_MARKER_BS + 1);
- }
-
- fn test_trim_end_whole_size(size: usize) {
- let (rest, result): (_, U256) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL.into());
- assert_eq!(
- rest.as_slice().len(),
- REDSTONE_MARKER_BS - size.min(REDSTONE_MARKER_BS)
- );
-
- let (_, result): (_, u64) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL);
-
- let (_, result): (_, usize) = test_trim_end(size);
- assert_eq!(result, 823907890102272usize);
-
- let (_rest, result): (_, Vec<u8>) = test_trim_end(size);
- assert_eq!(result.as_slice().len(), size.min(REDSTONE_MARKER_BS));
- }
-
- #[test]
- fn test_trim_end_u64() {
- let mut bytes = vec![255, 255, 255, 255, 255, 255, 255, 255, 255];
- let x: u64 = bytes.trim_end(8);
-
- let expected_bytes = vec![255];
-
- assert_eq!(bytes, expected_bytes);
- assert_eq!(x, 18446744073709551615);
- }
-
- #[should_panic(expected = "Number overflow: 18591708106338011145")]
- #[test]
- fn test_trim_end_u64_overflow() {
- let mut bytes = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9];
-
- let _: u64 = bytes.trim_end(9);
- }
-
- #[allow(dead_code)]
- trait TestTrimEnd<T>
- where
- Self: Sized,
- {
- fn test_trim_end(size: usize) -> (Self, T);
- }
-
- fn test_trim_end<T>(size: usize) -> (Vec<u8>, T)
- where
- Vec<u8>: Trim<T>,
- {
- let mut bytes = redstone_marker_bytes();
- let rest = bytes.trim_end(size);
- (bytes, rest)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -
pub trait TrimZeros {
- fn trim_zeros(self) -> Self;
-}
-
-impl TrimZeros for Vec<u8> {
- fn trim_zeros(self) -> Self {
- let mut res = self.len();
-
- for i in (0..self.len()).rev() {
- if self[i] != 0 {
- break;
- }
-
- res = i;
- }
-
- let (rest, _) = self.split_at(res);
-
- rest.into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{protocol::constants::REDSTONE_MARKER, utils::trim_zeros::TrimZeros};
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.as_slice().into()
- }
-
- #[test]
- fn test_trim_zeros() {
- let trimmed = redstone_marker_bytes().trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
-
- let trimmed = trimmed.trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
- }
-
- #[test]
- fn test_trim_zeros_empty() {
- let trimmed = Vec::<u8>::default().trim_zeros();
- assert_eq!(trimmed, Vec::<u8>::default());
- }
-}
-
fn:
) to \
- restrict the search to a given item kind.","Accepted kinds are: fn
, mod
, struct
, \
- enum
, trait
, type
, macro
, \
- and const
.","Search functions by type signature (e.g., vec -> usize
or \
- -> vec
or String, enum:Cow -> bool
)","You can look for items with an exact name by putting double quotes around \
- your request: \"string\"
","Look for functions that accept or return \
- slices and \
- arrays by writing \
- square brackets (e.g., -> [u8]
or [] -> Option
)","Look for items inside another one by searching for a path: vec::Vec
",].map(x=>""+x+"
").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="${value.replaceAll(" ", " ")}
`}else{error[index]=value}});output+=`Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,\nas it avoids reallocation if possible. Additionally, if the element type\nT
overrides clone_from()
, this will reuse the resources of self
’s\nelements as well.
let x = vec![5, 6, 7];\nlet mut y = vec![8, 9, 10];\nlet yp: *const i32 = y.as_ptr();\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no reallocation occurred\nassert_eq!(yp, y.as_ptr());
TYPE_ID
should give a unique identifier for its SBOR schema type.\nAn SBOR schema type capture details about the SBOR payload, how it should be interpreted, validated and displayed. Read moreget_local_type_data
, we need to ensure that the type and all of its own references\nget added to the aggregator. Read moreExtend implementation that copies elements out of references before pushing them onto the Vec.
\nThis implementation is specialized for slice iterators, where it uses copy_from_slice
to\nappend the entire slice at once.
extend_one
)extend_one
)extend_one
)extend_one
)Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has\nconstant time complexity.
\nConvert a clone-on-write slice into a vector.
\nIf s
already owns a Vec<T>
, it will be returned directly.\nIf s
is borrowing a slice, a new Vec<T>
will be allocated and\nfilled by cloning s
’s items into it.
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);\nlet b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);\nassert_eq!(Vec::from(o), Vec::from(b));
Turn a VecDeque<T>
into a Vec<T>
.
This never needs to re-allocate, but does need to do O(n) data movement if\nthe circular buffer doesn’t happen to be at the beginning of the allocation.
\nuse std::collections::VecDeque;\n\n// This one is *O*(1).\nlet deque: VecDeque<_> = (1..5).collect();\nlet ptr = deque.as_slices().0.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);\n\n// This one needs data rearranging.\nlet mut deque: VecDeque<_> = (1..5).collect();\ndeque.push_front(9);\ndeque.push_front(8);\nlet ptr = deque.as_slices().1.as_ptr();\nlet vec = Vec::from(deque);\nassert_eq!(vec, [8, 9, 1, 2, 3, 4]);\nassert_eq!(vec.as_ptr(), ptr);
Collects an iterator into a Vec, commonly called via Iterator::collect()
In general Vec
does not guarantee any particular growth or allocation strategy.\nThat also applies to this trait impl.
Note: This section covers implementation details and is therefore exempt from\nstability guarantees.
\nVec may use any or none of the following strategies,\ndepending on the supplied iterator:
\nIterator::size_hint()
\npushing
one item at a timeThe last case warrants some attention. It is an optimization that in many cases reduces peak memory\nconsumption and improves cache locality. But when big, short-lived allocations are created,\nonly a small fraction of their items get collected, no further use is made of the spare capacity\nand the resulting Vec
is moved into a longer-lived structure, then this can lead to the large\nallocations having their lifetimes unnecessarily extended which can result in increased memory\nfootprint.
In cases where this is an issue, the excess capacity can be discarded with Vec::shrink_to()
,\nVec::shrink_to_fit()
or by collecting into Box<[T]>
instead, which additionally reduces\nthe size of the long-lived struct.
static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());\n\nfor i in 0..10 {\n let big_temporary: Vec<u16> = (0..1024).collect();\n // discard most items\n let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();\n // without this a lot of unused capacity might be moved into the global\n result.shrink_to_fit();\n LONG_LIVED.lock().unwrap().push(result);\n}
The hash of a vector is the same as that of the corresponding slice,\nas required by the core::borrow::Borrow
implementation.
use std::hash::BuildHasher;\n\nlet b = std::hash::RandomState::new();\nlet v: Vec<u8> = vec![0xa8, 0x3c, 0x09];\nlet s: &[u8] = &[0xa8, 0x3c, 0x09];\nassert_eq!(b.hash_one(v), b.hash_one(s));
Creates a consuming iterator, that is, one that moves each value out of\nthe vector (from start to end). The vector cannot be used after calling\nthis.
\nlet v = vec![\"a\".to_string(), \"b\".to_string()];\nlet mut v_iter = v.into_iter();\n\nlet first_element: Option<String> = v_iter.next();\n\nassert_eq!(first_element, Some(\"a\".to_string()));\nassert_eq!(v_iter.next(), Some(\"b\".to_string()));\nassert_eq!(v_iter.next(), None);
Implements ordering of vectors, lexicographically.
\nImplements comparison of vectors, lexicographically.
\nself
and other
) and is used by the <=
\noperator. Read moreConstructs a new, empty Vec<T>
.
The vector will not allocate until elements are pushed onto it.
\nlet mut vec: Vec<i32> = Vec::new();
Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = Vec::with_capacity(10);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<()>::with_capacity(10);\nassert_eq!(vec_units.capacity(), usize::MAX);
try_with_capacity
)Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
Creates a Vec<T>
directly from a pointer, a length, and a capacity.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must have been allocated using the global allocator, such as via\nthe alloc::alloc
function.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to be the capacity that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is normally not safe\nto build a Vec<u8>
from a pointer to a C char
array with length\nsize_t
, doing so is only safe if the array was initially allocated by\na Vec
or String
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid\nthese issues, it is often preferable to do casting/transmuting using\nslice::from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
use std::ptr;\nuse std::mem;\n\nlet v = vec![1, 2, 3];\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts(p, len, cap);\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\nuse std::alloc::{alloc, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = alloc(layout).cast::<u32>();\n if mem.is_null() {\n return;\n }\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts(mem, 1, 16)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with value
.\nIf new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,\nin order to be able to clone the passed value.\nIf you need more flexibility (or want to rely on Default
instead of\nClone
), use Vec::resize_with
.\nIf you only need to resize to a smaller size, use Vec::truncate
.
let mut vec = vec![\"hello\"];\nvec.resize(3, \"world\");\nassert_eq!(vec, [\"hello\", \"world\", \"world\"]);\n\nlet mut vec = vec![1, 2, 3, 4];\nvec.resize(2, 0);\nassert_eq!(vec, [1, 2]);
Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends\nit to this Vec
. The other
slice is traversed in-order.
Note that this function is same as extend
except that it is\nspecialized to work with slices instead. If and when Rust gets\nspecialization this function will likely be deprecated (but still\navailable).
let mut vec = vec![1];\nvec.extend_from_slice(&[2, 3, 4]);\nassert_eq!(vec, [1, 2, 3, 4]);
Copies elements from src
range to the end of the vector.
Panics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut vec = vec![0, 1, 2, 3, 4];\n\nvec.extend_from_within(2..);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);\n\nvec.extend_from_within(..2);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);\n\nvec.extend_from_within(4..8);\nassert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
Creates a splicing iterator that replaces the specified range in the vector\nwith the given replace_with
iterator and yields the removed items.\nreplace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many elements are removed from the vector\nif the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
\nrange
) is empty,replace_with
yields fewer or equal elements than range
’s lengthsize_hint()
is exact.Otherwise, a temporary vector is allocated and the tail is moved twice.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nlet mut v = vec![1, 2, 3, 4];\nlet new = [7, 8, 9];\nlet u: Vec<_> = v.splice(1..3, new).collect();\nassert_eq!(v, &[1, 7, 8, 9, 4]);\nassert_eq!(u, &[2, 3]);
extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, then the element is removed and yielded.\nIf the closure returns false, the element will remain in the vector and will not be yielded\nby the iterator.
\nIf the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
\n\nlet mut i = 0;\nwhile i < vec.len() {\n if some_predicate(&mut vec[i]) {\n let val = vec.remove(i);\n // your code here\n } else {\n i += 1;\n }\n}\n
But extract_if
is easier to use. extract_if
is also more efficient,\nbecause it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate every element in the filter closure,\nregardless of whether you choose to keep or remove it.
Splitting an array into evens and odds, reusing the original allocation:
\n\n#![feature(extract_if)]\nlet mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];\n\nlet evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();\nlet odds = numbers;\n\nassert_eq!(evens, vec![2, 4, 6, 8, 14]);\nassert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
allocator_api
)Constructs a new, empty Vec<T, A>
.
The vector will not allocate until elements are pushed onto it.
\n#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec: Vec<i32, _> = Vec::new_in(System);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
It is important to note that although the returned vector has the\nminimum capacity specified, the vector will have a zero length. For\nan explanation of the difference between length and capacity, see\nCapacity and reallocation.
\nIf it is important to know the exact allocated capacity of a Vec
,\nalways use the capacity
method after construction.
For Vec<T, A>
where T
is a zero-sized type, there will be no allocation\nand the capacity will always be usize::MAX
.
Panics if the new capacity exceeds isize::MAX
bytes.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut vec = Vec::with_capacity_in(10, System);\n\n// The vector contains no items, even though it has capacity for more\nassert_eq!(vec.len(), 0);\nassert!(vec.capacity() >= 10);\n\n// These are all done without reallocating...\nfor i in 0..10 {\n vec.push(i);\n}\nassert_eq!(vec.len(), 10);\nassert!(vec.capacity() >= 10);\n\n// ...but this may make the vector reallocate\nvec.push(11);\nassert_eq!(vec.len(), 11);\nassert!(vec.capacity() >= 11);\n\n// A vector of a zero-sized type will always over-allocate, since no\n// allocation is necessary\nlet vec_units = Vec::<(), System>::with_capacity_in(10, System);\nassert_eq!(vec_units.capacity(), usize::MAX);
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity\nwith the provided allocator.
The vector will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the vector will not allocate.
Returns an error if the capacity exceeds isize::MAX
bytes,\nor if the allocator reports allocation failure.
allocator_api
)Creates a Vec<T, A>
directly from a pointer, a length, a capacity,\nand an allocator.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nptr
must be currently allocated via the given allocator alloc
.T
needs to have the same alignment as what ptr
was allocated with.\n(T
having a less strict alignment is not sufficient, the alignment really\nneeds to be equal to satisfy the dealloc
requirement that memory must be\nallocated and deallocated with the same layout.)T
times the capacity
(ie. the allocated size in bytes) needs\nto be the same size as the pointer was allocated with. (Because similar to\nalignment, dealloc
must be called with the same layout size
.)length
needs to be less than or equal to capacity
.length
values must be properly initialized values of type T
.capacity
needs to fit the layout size that the pointer was allocated with.isize::MAX
.\nSee the safety documentation of pointer::offset
.These requirements are always upheld by any ptr
that has been allocated\nvia Vec<T, A>
. Other allocation sources are allowed if the invariants are\nupheld.
Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example it is not safe\nto build a Vec<u8>
from a pointer to a C char
array with length size_t
.\nIt’s also not safe to build one from a Vec<u16>
and its length, because\nthe allocator cares about the alignment, and these two types have different\nalignments. The buffer was allocated with alignment 2 (for u16
), but after\nturning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the\nVec<T>
which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nuse std::ptr;\nuse std::mem;\n\nlet mut v = Vec::with_capacity_in(3, System);\nv.push(1);\nv.push(2);\nv.push(3);\n\n// Prevent running `v`'s destructor so we are in complete control\n// of the allocation.\nlet mut v = mem::ManuallyDrop::new(v);\n\n// Pull out the various important pieces of information about `v`\nlet p = v.as_mut_ptr();\nlet len = v.len();\nlet cap = v.capacity();\nlet alloc = v.allocator();\n\nunsafe {\n // Overwrite memory with 4, 5, 6\n for i in 0..len {\n ptr::write(p.add(i), 4 + i);\n }\n\n // Put everything back together into a Vec\n let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());\n assert_eq!(rebuilt, [4, 5, 6]);\n}
Using memory that was allocated elsewhere:
\n\n#![feature(allocator_api)]\n\nuse std::alloc::{AllocError, Allocator, Global, Layout};\n\nfn main() {\n let layout = Layout::array::<u32>(16).expect(\"overflow cannot happen\");\n\n let vec = unsafe {\n let mem = match Global.allocate(layout) {\n Ok(mem) => mem.cast::<u32>().as_ptr(),\n Err(AllocError) => return,\n };\n\n mem.write(1_000_000);\n\n Vec::from_raw_parts_in(mem, 1, 16, Global)\n };\n\n assert_eq!(vec, &[1_000_000]);\n assert_eq!(vec.capacity(), 16);\n}
vec_into_raw_parts
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity)
.
Returns the raw pointer to the underlying data, the length of\nthe vector (in elements), and the allocated capacity of the\ndata (in elements). These are the same arguments in the same\norder as the arguments to from_raw_parts
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts
function, allowing\nthe destructor to perform the cleanup.
#![feature(vec_into_raw_parts)]\nlet v: Vec<i32> = vec![-1, 0, 1];\n\nlet (ptr, len, cap) = v.into_raw_parts();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts(ptr, len, cap)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
allocator_api
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity, allocator)
.
Returns the raw pointer to the underlying data, the length of the vector (in elements),\nthe allocated capacity of the data (in elements), and the allocator. These are the same\narguments in the same order as the arguments to from_raw_parts_in
.
After calling this function, the caller is responsible for the\nmemory previously managed by the Vec
. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a Vec
with the from_raw_parts_in
function, allowing\nthe destructor to perform the cleanup.
#![feature(allocator_api, vec_into_raw_parts)]\n\nuse std::alloc::System;\n\nlet mut v: Vec<i32, System> = Vec::new_in(System);\nv.push(-1);\nv.push(0);\nv.push(1);\n\nlet (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();\n\nlet rebuilt = unsafe {\n // We can now make changes to the components, such as\n // transmuting the raw pointer to a compatible type.\n let ptr = ptr as *mut u32;\n\n Vec::from_raw_parts_in(ptr, len, cap, alloc)\n};\nassert_eq!(rebuilt, [4294967295, 0, 1]);
Returns the total number of elements the vector can hold without\nreallocating.
\nlet mut vec: Vec<i32> = Vec::with_capacity(10);\nvec.push(42);\nassert!(vec.capacity() >= 10);
Reserves capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to\nspeculatively avoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve(10);\nassert!(vec.capacity() >= 11);
Reserves the minimum capacity for at least additional
more elements to\nbe inserted in the given Vec<T>
. Unlike reserve
, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact
, capacity will be greater than or equal to\nself.len() + additional
. Does nothing if the capacity is already\nsufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer reserve
if future insertions are expected.
Panics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1];\nvec.reserve_exact(10);\nassert!(vec.capacity() >= 11);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the given Vec<T>
. The collection may reserve more space to speculatively avoid\nfrequent reallocations. After calling try_reserve
, capacity will be\ngreater than or equal to self.len() + additional
if it returns\nOk(())
. Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Tries to reserve the minimum capacity for at least additional
\nelements to be inserted in the given Vec<T>
. Unlike try_reserve
,\nthis will not deliberately over-allocate to speculatively avoid frequent\nallocations. After calling try_reserve_exact
, capacity will be greater\nthan or equal to self.len() + additional
if it returns Ok(())
.\nDoes nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve
if future insertions are expected.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {\n let mut output = Vec::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve_exact(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.extend(data.iter().map(|&val| {\n val * 2 + 5 // very complicated\n }));\n\n Ok(output)\n}
Shrinks the capacity of the vector as much as possible.
\nThe behavior of this method depends on the allocator, which may either shrink the vector\nin-place or reallocate. The resulting vector might still have some excess capacity, just as\nis the case for with_capacity
. See Allocator::shrink
for more details.
let mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to_fit();\nassert!(vec.capacity() >= 3);
Shrinks the capacity of the vector with a lower bound.
\nThe capacity will remain at least as large as both the length\nand the supplied value.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\nassert!(vec.capacity() >= 10);\nvec.shrink_to(4);\nassert!(vec.capacity() >= 4);\nvec.shrink_to(0);\nassert!(vec.capacity() >= 3);
Converts the vector into Box<[T]>
.
Before doing the conversion, this method discards excess capacity like shrink_to_fit
.
let v = vec![1, 2, 3];\n\nlet slice = v.into_boxed_slice();
Any excess capacity is removed:
\n\nlet mut vec = Vec::with_capacity(10);\nvec.extend([1, 2, 3]);\n\nassert!(vec.capacity() >= 10);\nlet slice = vec.into_boxed_slice();\nassert_eq!(slice.into_vec().capacity(), 3);
Shortens the vector, keeping the first len
elements and dropping\nthe rest.
If len
is greater or equal to the vector’s current length, this has\nno effect.
The drain
method can emulate truncate
, but causes the excess\nelements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity\nof the vector.
\nTruncating a five element vector to two elements:
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nvec.truncate(2);\nassert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current\nlength:
let mut vec = vec![1, 2, 3];\nvec.truncate(8);\nassert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
\nmethod.
let mut vec = vec![1, 2, 3];\nvec.truncate(0);\nassert_eq!(vec, []);
Extracts a slice containing the entire vector.
\nEquivalent to &s[..]
.
use std::io::{self, Write};\nlet buffer = vec![1, 2, 3, 5, 8];\nio::sink().write(buffer.as_slice()).unwrap();
Extracts a mutable slice of the entire vector.
\nEquivalent to &mut s[..]
.
use std::io::{self, Read};\nlet mut buffer = vec![0; 3];\nio::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer\nvalid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThe caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell
) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize mutable references to the slice,\nor mutable references to specific elements you are planning on accessing through this pointer,\nas well as writing to those elements, may still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
let x = vec![1, 2, 4];\nlet x_ptr = x.as_ptr();\n\nunsafe {\n for i in 0..x.len() {\n assert_eq!(*x_ptr.add(i), 1 << i);\n }\n}
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0, 1, 2];\n let ptr1 = v.as_ptr();\n let _ = ptr1.read();\n let ptr2 = v.as_mut_ptr().offset(2);\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`\n // because it mutated a different element:\n let _ = ptr1.read();\n}
Returns an unsafe mutable pointer to the vector’s buffer, or a dangling\nraw pointer valid for zero sized reads if the vector didn’t allocate.
\nThe caller must ensure that the vector outlives the pointer this\nfunction returns, or else it will end up pointing to garbage.\nModifying the vector may cause its buffer to be reallocated,\nwhich would also make any pointers to it invalid.
\nThis method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying slice, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr
and as_mut_ptr
.\nNote that calling other methods that materialize references to the slice,\nor references to specific elements you are planning on accessing through this pointer,\nmay still invalidate this pointer.\nSee the second example below for how this guarantee can be used.
// Allocate vector big enough for 4 elements.\nlet size = 4;\nlet mut x: Vec<i32> = Vec::with_capacity(size);\nlet x_ptr = x.as_mut_ptr();\n\n// Initialize elements via raw pointer writes, then set length.\nunsafe {\n for i in 0..size {\n *x_ptr.add(i) = i as i32;\n }\n x.set_len(size);\n}\nassert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
\n\nunsafe {\n let mut v = vec![0];\n let ptr1 = v.as_mut_ptr();\n ptr1.write(1);\n let ptr2 = v.as_mut_ptr();\n ptr2.write(2);\n // Notably, the write to `ptr2` did *not* invalidate `ptr1`:\n ptr1.write(3);\n}
allocator_api
)Returns a reference to the underlying allocator.
\nForces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal\ninvariants of the type. Normally changing the length of a vector\nis done using one of the safe operations instead, such as\ntruncate
, resize
, extend
, or clear
.
new_len
must be less than or equal to capacity()
.old_len..new_len
must be initialized.This method can be useful for situations in which the vector\nis serving as a buffer for other code, particularly over FFI:
\n\npub fn get_dictionary(&self) -> Option<Vec<u8>> {\n // Per the FFI method's docs, \"32768 bytes is always enough\".\n let mut dict = Vec::with_capacity(32_768);\n let mut dict_length = 0;\n // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:\n // 1. `dict_length` elements were initialized.\n // 2. `dict_length` <= the capacity (32_768)\n // which makes `set_len` safe to call.\n unsafe {\n // Make the FFI call...\n let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);\n if r == Z_OK {\n // ...and update the length to what was initialized.\n dict.set_len(dict_length);\n Some(dict)\n } else {\n None\n }\n }\n}
While the following example is sound, there is a memory leak since\nthe inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],\n vec![0, 1, 0],\n vec![0, 0, 1]];\n// SAFETY:\n// 1. `old_len..0` is empty so no elements need to be initialized.\n// 2. `0 <= capacity` always holds whatever `capacity` is.\nunsafe {\n vec.set_len(0);\n}
Normally, here, one would use clear
instead to correctly drop\nthe contents and thus not leak memory.
Removes an element from the vector and returns it.
\nThe removed element is replaced by the last element of the vector.
\nThis does not preserve ordering of the remaining elements, but is O(1).\nIf you need to preserve the element order, use remove
instead.
Panics if index
is out of bounds.
let mut v = vec![\"foo\", \"bar\", \"baz\", \"qux\"];\n\nassert_eq!(v.swap_remove(1), \"bar\");\nassert_eq!(v, [\"foo\", \"qux\", \"baz\"]);\n\nassert_eq!(v.swap_remove(0), \"foo\");\nassert_eq!(v, [\"baz\", \"qux\"]);
Inserts an element at position index
within the vector, shifting all\nelements after it to the right.
Panics if index > len
.
let mut vec = vec![1, 2, 3];\nvec.insert(1, 4);\nassert_eq!(vec, [1, 4, 2, 3]);\nvec.insert(4, 5);\nassert_eq!(vec, [1, 4, 2, 3, 5]);
Takes O(Vec::len
) time. All items after the insertion index must be\nshifted to the right. In the worst case, all elements are shifted when\nthe insertion index is 0.
Removes and returns the element at position index
within the vector,\nshifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a\nworst-case performance of O(n). If you don’t need the order of elements\nto be preserved, use swap_remove
instead. If you’d like to remove\nelements from the beginning of the Vec
, consider using\nVecDeque::pop_front
instead.
Panics if index
is out of bounds.
let mut v = vec![1, 2, 3];\nassert_eq!(v.remove(1), 2);\nassert_eq!(v, [1, 3]);
Retains only the elements specified by the predicate.
\nIn other words, remove all elements e
for which f(&e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain(|&x| x % 2 == 0);\nassert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.
\n\nlet mut vec = vec![1, 2, 3, 4, 5];\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\nvec.retain(|_| *iter.next().unwrap());\nassert_eq!(vec, [2, 3, 5]);
Retains only the elements specified by the predicate, passing a mutable reference to it.
\nIn other words, remove all elements e
such that f(&mut e)
returns false
.\nThis method operates in place, visiting each element exactly once in the\noriginal order, and preserves the order of the retained elements.
let mut vec = vec![1, 2, 3, 4];\nvec.retain_mut(|x| if *x <= 3 {\n *x += 1;\n true\n} else {\n false\n});\nassert_eq!(vec, [2, 3, 4]);
Removes all but the first of consecutive elements in the vector that resolve to the same\nkey.
\nIf the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![10, 20, 21, 30, 20];\n\nvec.dedup_by_key(|i| *i / 10);\n\nassert_eq!(vec, [10, 20, 30, 20]);
Removes all but the first of consecutive elements in the vector satisfying a given equality\nrelation.
\nThe same_bucket
function is passed references to two elements from the vector and\nmust determine if the elements compare equal. The elements are passed in opposite order\nfrom their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
\nlet mut vec = vec![\"foo\", \"bar\", \"Bar\", \"baz\", \"bar\"];\n\nvec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));\n\nassert_eq!(vec, [\"foo\", \"bar\", \"baz\", \"bar\"]);
Appends an element to the back of a collection.
\nPanics if the new capacity exceeds isize::MAX
bytes.
let mut vec = vec![1, 2];\nvec.push(3);\nassert_eq!(vec, [1, 2, 3]);
Takes amortized O(1) time. If the vector’s length would exceed its\ncapacity after the push, O(capacity) time is taken to copy the\nvector’s elements to a larger allocation. This expensive operation is\noffset by the capacity O(1) insertions it allows.
\nvec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned\nwith the element.
\nUnlike push
this method will not reallocate when there’s insufficient capacity.\nThe caller should use reserve
or try_reserve
to ensure that there is enough capacity.
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]\n\nuse std::collections::TryReserveError;\nfn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {\n let mut vec = Vec::new();\n for value in iter {\n if let Err(value) = vec.push_within_capacity(value) {\n vec.try_reserve(1)?;\n // this cannot fail, the previous line either returned or added at least 1 free slot\n let _ = vec.push_within_capacity(value);\n }\n }\n Ok(vec)\n}\nassert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
Takes O(1) time.
\nRemoves the last element from a vector and returns it, or None
if it\nis empty.
If you’d like to pop the first element, consider using\nVecDeque::pop_front
instead.
let mut vec = vec![1, 2, 3];\nassert_eq!(vec.pop(), Some(3));\nassert_eq!(vec, [1, 2]);
Takes O(1) time.
\nvec_pop_if
)Removes and returns the last element in a vector if the predicate\nreturns true
, or None
if the predicate returns false or the vector\nis empty.
#![feature(vec_pop_if)]\n\nlet mut vec = vec![1, 2, 3, 4];\nlet pred = |x: &mut i32| *x % 2 == 0;\n\nassert_eq!(vec.pop_if(pred), Some(4));\nassert_eq!(vec, [1, 2, 3]);\nassert_eq!(vec.pop_if(pred), None);
Removes the specified range from the vector in bulk, returning all\nremoved elements as an iterator. If the iterator is dropped before\nbeing fully consumed, it drops the remaining removed elements.
\nThe returned iterator keeps a mutable borrow on the vector to optimize\nits implementation.
\nPanics if the starting point is greater than the end point or if\nthe end point is greater than the length of the vector.
\nIf the returned iterator goes out of scope without being dropped (due to\nmem::forget
, for example), the vector may have lost and leaked\nelements arbitrarily, including elements outside the range.
let mut v = vec![1, 2, 3];\nlet u: Vec<_> = v.drain(1..).collect();\nassert_eq!(v, &[1]);\nassert_eq!(u, &[2, 3]);\n\n// A full range clears the vector, like `clear()` does\nv.drain(..);\nassert_eq!(v, &[]);
Clears the vector, removing all values.
\nNote that this method has no effect on the allocated capacity\nof the vector.
\nlet mut v = vec![1, 2, 3];\n\nv.clear();\n\nassert!(v.is_empty());
Returns the number of elements in the vector, also referred to\nas its ‘length’.
\nlet a = vec![1, 2, 3];\nassert_eq!(a.len(), 3);
Returns true
if the vector contains no elements.
let mut v = Vec::new();\nassert!(v.is_empty());\n\nv.push(1);\nassert!(!v.is_empty());
Splits the collection into two at the given index.
\nReturns a newly allocated vector containing the elements in the range\n[at, len)
. After the call, the original vector will be left containing\nthe elements [0, at)
with its previous capacity unchanged.
mem::take
or mem::replace
.Vec::truncate
.Vec::drain
.Panics if at > len
.
let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the\ndifference, with each additional slot filled with the result of\ncalling the closure f
. The return values from f
will end up\nin the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If\nyou’d rather Clone
a given value, use Vec::resize
. If you\nwant to use the Default
trait to generate values, you can\npass Default::default
as the second argument.
let mut vec = vec![1, 2, 3];\nvec.resize_with(5, Default::default);\nassert_eq!(vec, [1, 2, 3, 0, 0]);\n\nlet mut vec = vec![];\nlet mut p = 1;\nvec.resize_with(4, || { p *= 2; p });\nassert_eq!(vec, [2, 4, 8, 16]);
Consumes and leaks the Vec
, returning a mutable reference to the contents,\n&'a mut [T]
. Note that the type T
must outlive the chosen lifetime\n'a
. If the type has only static references, or none at all, then this\nmay be chosen to be 'static
.
As of Rust 1.57, this method does not reallocate or shrink the Vec
,\nso the leaked allocation may include unused capacity that is not part\nof the returned slice.
This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak.
\nSimple usage:
\n\nlet x = vec![1, 2, 3];\nlet static_ref: &'static mut [usize] = x.leak();\nstatic_ref[0] += 1;\nassert_eq!(static_ref, &[2, 2, 3]);
Returns the remaining spare capacity of the vector as a slice of\nMaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by\nreading from a file) before marking the data as initialized using the\nset_len
method.
// Allocate vector big enough for 10 elements.\nlet mut v = Vec::with_capacity(10);\n\n// Fill in the first 3 elements.\nlet uninit = v.spare_capacity_mut();\nuninit[0].write(0);\nuninit[1].write(1);\nuninit[2].write(2);\n\n// Mark the first 3 elements of the vector as being initialized.\nunsafe {\n v.set_len(3);\n}\n\nassert_eq!(&v, &[0, 1, 2]);
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare\ncapacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data\n(e.g. by reading from a file) before marking the data as initialized using\nthe set_len
method.
Note that this is a low-level API, which should be used with care for\noptimization purposes. If you need to append data to a Vec
\nyou can use push
, extend
, extend_from_slice
,\nextend_from_within
, insert
, append
, resize
or\nresize_with
, depending on your exact needs.
#![feature(vec_split_at_spare)]\n\nlet mut v = vec![1, 1, 2];\n\n// Reserve additional space big enough for 10 elements.\nv.reserve(10);\n\nlet (init, uninit) = v.split_at_spare_mut();\nlet sum = init.iter().copied().sum::<u32>();\n\n// Fill in the next 4 elements.\nuninit[0].write(sum);\nuninit[1].write(sum * 2);\nuninit[2].write(sum * 3);\nuninit[3].write(sum * 4);\n\n// Mark the 4 elements of the vector as being initialized.\nunsafe {\n let len = v.len();\n v.set_len(len + 4);\n}\n\nassert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
pub(crate) fn aggregate_values(
- config: Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<U256>
Aggregates values from a collection of data packages according to the provided configuration.
-This function takes a configuration and a vector of data packages, constructs a matrix of values
-and their corresponding signers, and then aggregates these values based on the aggregation logic
-defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-an average of the values, selecting the median, or applying a custom algorithm defined within the
-aggregate_matrix
function.
The primary purpose of this function is to consolidate data from multiple sources into a coherent
-and singular value set that adheres to the criteria specified in the Config
.
config
- A Config
instance containing settings and parameters used to guide the aggregation process.data_packages
- A vector of DataPackage
instances, each representing a set of values and associated
-metadata collected from various sources or signers.Returns a Vec<U256>
, which is a vector of aggregated values resulting from applying the aggregation
-logic to the input data packages as per the specified configuration. Each U256
value in the vector
-represents an aggregated result derived from the corresponding data packages.
This function is internal to the crate (pub(crate)
) and not exposed as part of the public API. It is
-designed to be used by other components within the same crate that require value aggregation functionality.
fn make_value_signer_matrix(
- config: &Config,
- data_packages: Vec<DataPackage>,
-) -> Vec<Vec<Option<U256>>>
pub struct Config {
- pub signer_count_threshold: u8,
- pub signers: Vec<Bytes>,
- pub feed_ids: Vec<U256>,
- pub block_timestamp: u64,
-}
Configuration for a RedStone payload processor.
-Specifies the parameters necessary for the verification and aggregation of values -from various data points passed by the RedStone payload.
-signer_count_threshold: u8
The minimum number of signers required validating the data.
-Specifies how many unique signers (from different addresses) are required -for the data to be considered valid and trustworthy.
-signers: Vec<Bytes>
List of identifiers for signers authorized to sign the data.
-Each signer is identified by a unique, network-specific byte string (Bytes
),
-which represents their address.
feed_ids: Vec<U256>
Identifiers for the data feeds from which values are aggregated.
-Each data feed id is represented by the network-specific U256
type.
block_timestamp: u64
The current block time in timestamp format, used for verifying data timeliness.
-The value’s been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows -for determining whether the data is current in the context of blockchain time.
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult
pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult
The main processor of the RedStone payload.
-config
- Configuration of the payload processing.payload_bytes
- Network-specific byte-list of the payload to be processed.pub struct ProcessorResult {
- pub min_timestamp: u64,
- pub values: Vec<U256>,
-}
Represents the result of processing the RedStone payload.
-This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-particularly focusing on time-sensitive data and its associated values, according to the Config
.
min_timestamp: u64
The minimum timestamp encountered during processing.
-This field captures the earliest time point (in milliseconds since the Unix epoch) -among the processed data packages, indicating the starting boundary of the dataset’s time range.
-values: Vec<U256>
A collection of values processed during the operation.
-Each element in this vector represents a processed value corresponding
-to the passed data_feed item in the Config
.
self
and other
values to be equal, and is used
-by ==
.pub(crate) trait Validator {
- // Required methods
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
- fn validate_signer_count_threshold(
- &self,
- index: usize,
- values: &[Option<U256>],
- ) -> Vec<U256>;
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
A trait defining validation operations for data feeds and signers.
-This trait specifies methods for validating aspects of data feeds and signers within a system that -requires data integrity and authenticity checks. Implementations of this trait are responsible for -defining the logic behind each validation step, ensuring that data conforms to expected rules and -conditions.
-Retrieves the index of a given data feed.
-This method takes a feed_id
representing the unique identifier of a data feed and
-returns an Option<usize>
indicating the index of the feed within a collection of feeds.
-If the feed does not exist, None
is returned.
feed_id
: U256
- The unique identifier of the data feed.Option<usize>
- The index of the feed if it exists, or None
if it does not.Retrieves the index of a given signer.
-This method accepts a signer identifier in the form of a byte slice and returns an
-Option<usize>
indicating the signer’s index within a collection of signers. If the signer
-is not found, None
is returned.
signer
: &[u8]
- A byte slice representing the signer’s identifier.Option<usize>
- The index of the signer if found, or None
if not found.Validates the signer count threshold for a given index within a set of values.
-This method is responsible for ensuring that the number of valid signers meets or exceeds
-a specified threshold necessary for a set of data values to be considered valid. It returns
-a vector of U256
if the values pass the validation, to be processed in other steps.
index
: usize
- The index of the data value being validated.values
: &[Option<U256>]
- A slice of optional U256
values associated with the data.Vec<U256>
- A vector of U256
values that meet the validation criteria.Validates the timestamp for a given index.
-This method checks whether a timestamp associated with a data value at a given index -meets specific conditions (e.g., being within an acceptable time range). It returns -the validated timestamp if it’s valid, to be processed in other steps.
-index
: usize
- The index of the data value whose timestamp is being validated.timestamp
: u64
- The timestamp to be validated.u64
- The validated timestamp.redstone
is a collection of utilities to make deserializing&decrypting RedStone payload.
-It includes a pure Rust implementation, along with extensions for certain networks.
Different crypto-mechanisms are easily injectable.
-The current implementation contains secp256k1
- and k256
-based variants.
Redirecting to macro.print_and_panic.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_and_panic.html b/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_and_panic.html deleted file mode 100644 index b308eb68..00000000 --- a/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_and_panic.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_and_panic { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
Redirecting to macro.print_debug.html...
- - - \ No newline at end of file diff --git a/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_debug.html b/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_debug.html deleted file mode 100644 index 3cb863d6..00000000 --- a/static/rust/redstone/crypto_secp256k1/doc/redstone/macro.print_debug.html +++ /dev/null @@ -1,4 +0,0 @@ -macro_rules! print_debug { - ($fmt:expr) => { ... }; - ($fmt:expr, $($args:tt)*) => { ... }; -}
pub trait AsAsciiStr {
- // Required method
- fn as_ascii_str(&self) -> String;
-}
pub trait AsHexStr {
- // Required method
- fn as_hex_str(&self) -> String;
-}
pub trait Assert<F> {
- // Required method
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
pub trait Unwrap<R> {
- type ErrorArg;
-
- // Required method
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
pub enum Error {
- ContractError(Box<dyn ContractErrorContent>),
- NumberOverflow(U256),
- ArrayIsEmpty,
- CryptographicError(usize),
- SizeNotSupported(usize),
- WrongRedStoneMarker(Vec<u8>),
- NonEmptyPayloadRemainder(Vec<u8>),
- InsufficientSignerCount(usize, usize, U256),
- TimestampTooOld(usize, u64),
- TimestampTooFuture(usize, u64),
- ClonedContractError(u8, String),
-}
Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-These errors include issues with contract logic, data types, -cryptographic operations, and conditions specific to the requirements.
-Represents errors that arise from the contract itself.
-This variant is used for encapsulating errors that are specific to the contract’s logic -or execution conditions that aren’t covered by more specific error types.
-Indicates an overflow error with U256
numbers.
Used when operations on U256
numbers exceed their maximum value, potentially leading
-to incorrect calculations or state.
Used when an expected non-empty array or vector is found to be empty.
-This could occur in scenarios where the contract logic requires a non-empty collection -of items for the correct operation, for example, during aggregating the values.
-Represents errors related to cryptographic operations.
-This includes failures in signature verification, hashing, or other cryptographic -processes, with the usize indicating the position or identifier of the failed operation.
-Signifies that an unsupported size was encountered.
-This could be used when a data structure or input does not meet the expected size -requirements for processing.
-Indicates that the marker bytes for RedStone are incorrect.
-This error is specific to scenarios where marker or identifier bytes do not match -expected values, potentially indicating corrupted or tampered data.
-Used when there is leftover data in a payload that should have been empty.
-This could indicate an error in data parsing or that additional, unexpected data -was included in a message or transaction.
-Indicates that the number of signers does not meet the required threshold.
-This variant includes the current number of signers, the required threshold, and -potentially a feed_id related to the operation that failed due to insufficient signers.
-Used when a timestamp is older than allowed by the processor logic.
-Includes the position or identifier of the timestamp and the threshold value, -indicating that the provided timestamp is too far in the past.
-Indicates that a timestamp is further in the future than allowed.
-Similar to TimestampTooOld
, but for future timestamps exceeding the contract’s
-acceptance window.
Represents errors that need to clone ContractErrorContent
, which is not supported by default.
This variant allows for the manual duplication of contract error information, including -an error code and a descriptive message.
-pub trait FromBytesRepr<T> {
- // Required method
- fn from_bytes_repr(bytes: T) -> Self;
-}
pub struct Std;
pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- // Required methods
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage
pub(crate) fn trim_data_packages(
- payload: &mut Vec<u8>,
- count: usize,
-) -> Vec<DataPackage>
pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
signer_address: Vec<u8>
§timestamp: u64
§data_points: Vec<DataPoint>
source
. Read moreself
and other
values to be equal, and is used
-by ==
.fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint
pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
feed_id: U256
§value: U256
pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
data_packages: Vec<DataPackage>
pub(crate) trait FilterSome<Output> {
- // Required method
- fn filter_some(&self) -> Output;
-}
fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>where
- T: PartialOrd,
trait Averageable: Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy { }
pub trait TrimZeros {
- // Required method
- fn trim_zeros(self) -> Self;
-}
U::from(self)
.\nThe minimum number of signers required validating the data.\nList of identifiers for signers authorized to sign the …\nThe main processor of the RedStone payload.\nRepresents the result of processing the RedStone payload.\nReturns the argument unchanged.\nCalls U::from(self)
.\nThe minimum timestamp encountered during processing.\nA collection of values processed during the operation.\nA trait defining validation operations for data feeds and …\nRetrieves the index of a given data feed.\nRetrieves the index of a given signer.\nValidates the signer count threshold for a given index …\nValidates the timestamp for a given index.\nUsed when an expected non-empty array or vector is found …\nRepresents errors that need to clone ContractErrorContent
, …\nRepresents errors that arise from the contract itself.\nRepresents errors related to cryptographic operations.\nErrors that can be encountered in the …\nIndicates that the number of signers does not meet the …\nUsed when there is leftover data in a payload that should …\nIndicates an overflow error with U256
numbers.\nSignifies that an unsupported size was encountered.\nIndicates that a timestamp is further in the future than …\nUsed when a timestamp is older than allowed by the …\nIndicates that the marker bytes for RedStone are incorrect.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.\nReturns the argument unchanged.\nCalls U::from(self)
.")
\ No newline at end of file
diff --git a/static/rust/redstone/crypto_secp256k1/doc/settings.html b/static/rust/redstone/crypto_secp256k1/doc/settings.html
deleted file mode 100644
index 9631dcb2..00000000
--- a/static/rust/redstone/crypto_secp256k1/doc/settings.html
+++ /dev/null
@@ -1 +0,0 @@
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -
use crate::{
- core::{config::Config, validator::Validator},
- network::specific::U256,
- print_debug,
- protocol::data_package::DataPackage,
- utils::median::Median,
-};
-
-type Matrix = Vec<Vec<Option<U256>>>;
-
-/// Aggregates values from a collection of data packages according to the provided configuration.
-///
-/// This function takes a configuration and a vector of data packages, constructs a matrix of values
-/// and their corresponding signers, and then aggregates these values based on the aggregation logic
-/// defined in the provided configuration. The aggregation strategy could vary, for example, by taking
-/// an average of the values, selecting the median, or applying a custom algorithm defined within the
-/// `aggregate_matrix` function.
-///
-/// The primary purpose of this function is to consolidate data from multiple sources into a coherent
-/// and singular value set that adheres to the criteria specified in the `Config`.
-///
-/// # Arguments
-///
-/// * `config` - A `Config` instance containing settings and parameters used to guide the aggregation process.
-/// * `data_packages` - A vector of `DataPackage` instances, each representing a set of values and associated
-/// metadata collected from various sources or signers.
-///
-/// # Returns
-///
-/// Returns a `Vec<U256>`, which is a vector of aggregated values resulting from applying the aggregation
-/// logic to the input data packages as per the specified configuration. Each `U256` value in the vector
-/// represents an aggregated result derived from the corresponding data packages.
-///
-/// # Note
-///
-/// This function is internal to the crate (`pub(crate)`) and not exposed as part of the public API. It is
-/// designed to be used by other components within the same crate that require value aggregation functionality.
-pub(crate) fn aggregate_values(config: Config, data_packages: Vec<DataPackage>) -> Vec<U256> {
- aggregate_matrix(make_value_signer_matrix(&config, data_packages), config)
-}
-
-fn aggregate_matrix(matrix: Matrix, config: Config) -> Vec<U256> {
- matrix
- .iter()
- .enumerate()
- .map(|(index, values)| {
- config
- .validate_signer_count_threshold(index, values)
- .median()
- })
- .collect()
-}
-
-fn make_value_signer_matrix(config: &Config, data_packages: Vec<DataPackage>) -> Matrix {
- let mut matrix = vec![vec![None; config.signers.len()]; config.feed_ids.len()];
-
- data_packages.iter().for_each(|data_package| {
- if let Some(signer_index) = config.signer_index(&data_package.signer_address) {
- data_package.data_points.iter().for_each(|data_point| {
- if let Some(feed_index) = config.feed_index(data_point.feed_id) {
- matrix[feed_index][signer_index] = data_point.value.into()
- }
- })
- }
- });
-
- print_debug!("{:?}", matrix);
-
- matrix
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod aggregate_matrix_tests {
- use crate::{
- core::{aggregator::aggregate_matrix, config::Config},
- helpers::iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- };
-
- #[test]
- fn test_aggregate_matrix() {
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8, 23].iter_into_opt(),
- ];
-
- for signer_count_threshold in 0..Config::test().signers.len() + 1 {
- let mut config = Config::test();
- config.signer_count_threshold = signer_count_threshold as u8;
-
- let result = aggregate_matrix(matrix.clone(), config);
-
- assert_eq!(result, vec![12u8, 22].iter_into());
- }
- }
-
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_one_value() {
- let mut config = Config::test();
- config.signer_count_threshold = 1;
-
- let matrix = vec![
- vec![11u8, 13].iter_into_opt(),
- vec![21u8.into(), None].opt_iter_into_opt(),
- ];
-
- let result = aggregate_matrix(matrix, config);
-
- assert_eq!(result, vec![12u8, 21].iter_into());
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_aggregate_matrix_smaller_threshold_missing_whole_feed() {
- let mut config = Config::test();
- config.signer_count_threshold = 0;
-
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, config);
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #0 (ETH)")]
- #[test]
- fn test_aggregate_matrix_missing_one_value() {
- let matrix = vec![
- vec![21u8.into(), None].opt_iter_into_opt(),
- vec![11u8, 12].iter_into_opt(),
- ];
-
- aggregate_matrix(matrix, Config::test());
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #1 (BTC)")]
- #[test]
- fn test_aggregate_matrix_missing_whole_feed() {
- let matrix = vec![vec![11u8, 13].iter_into_opt(), vec![None; 2]];
-
- aggregate_matrix(matrix, Config::test());
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod make_value_signer_matrix {
- use crate::{
- core::{
- aggregator::{make_value_signer_matrix, Matrix},
- config::Config,
- test_helpers::{AVAX, BTC, ETH, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2},
- },
- helpers::iter_into::IterInto,
- network::specific::U256,
- protocol::data_package::DataPackage,
- };
-
- #[test]
- fn test_make_value_signer_matrix_empty() {
- let config = Config::test();
-
- test_make_value_signer_matrix_of(
- vec![],
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_exact() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_greater() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![21, 22].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_smaller() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_diagonal() {
- let data_packages = vec![
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11.into(), None], vec![None, 22.into()]],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_repetitions() {
- let data_packages = vec![
- DataPackage::test(BTC, 21, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(BTC, 22, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(BTC, 202, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 101, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![101, 12].iter_into(), vec![21, 202].iter_into()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_all_wrong() {
- let config = Config::test();
-
- let data_packages = vec![
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![None; config.signers.len()]; config.feed_ids.len()],
- );
- }
-
- #[test]
- fn test_make_value_signer_matrix_mix() {
- let data_packages = vec![
- DataPackage::test(ETH, 11, TEST_SIGNER_ADDRESS_1, None),
- DataPackage::test(ETH, 12, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 32, TEST_SIGNER_ADDRESS_2, None),
- DataPackage::test(AVAX, 31, TEST_SIGNER_ADDRESS_1, None),
- ];
-
- test_make_value_signer_matrix_of(
- data_packages,
- vec![vec![11, 12].iter_into(), vec![None; 2]],
- );
- }
-
- fn test_make_value_signer_matrix_of(
- data_packages: Vec<DataPackage>,
- expected_values: Vec<Vec<Option<u128>>>,
- ) {
- let config = &Config::test();
- let result = make_value_signer_matrix(config, data_packages);
-
- let expected_matrix: Matrix = expected_values
- .iter()
- .map(|row| {
- (row.iter()
- .map(|&value| value.map(U256::from))
- .collect::<Vec<_>>())
- .iter_into() as Vec<Option<U256>>
- })
- .collect();
-
- assert_eq!(result, expected_matrix)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -
use crate::network::specific::{Bytes, U256};
-
-/// Configuration for a RedStone payload processor.
-///
-/// Specifies the parameters necessary for the verification and aggregation of values
-/// from various data points passed by the RedStone payload.
-#[derive(Debug)]
-pub struct Config {
- /// The minimum number of signers required validating the data.
- ///
- /// Specifies how many unique signers (from different addresses) are required
- /// for the data to be considered valid and trustworthy.
- pub signer_count_threshold: u8,
-
- /// List of identifiers for signers authorized to sign the data.
- ///
- /// Each signer is identified by a unique, network-specific byte string (`Bytes`),
- /// which represents their address.
- pub signers: Vec<Bytes>,
-
- /// Identifiers for the data feeds from which values are aggregated.
- ///
- /// Each data feed id is represented by the network-specific `U256` type.
- pub feed_ids: Vec<U256>,
-
- /// The current block time in timestamp format, used for verifying data timeliness.
- ///
- /// The value's been expressed in milliseconds since the Unix epoch (January 1, 1970) and allows
- /// for determining whether the data is current in the context of blockchain time.
- pub block_timestamp: u64,
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -
use crate::{
- core::{
- aggregator::aggregate_values, config::Config, processor_result::ProcessorResult,
- validator::Validator,
- },
- network::specific::Bytes,
- print_debug,
- protocol::payload::Payload,
-};
-
-/// The main processor of the RedStone payload.
-///
-///
-/// # Arguments
-///
-/// * `config` - Configuration of the payload processing.
-/// * `payload_bytes` - Network-specific byte-list of the payload to be processed.
-pub fn process_payload(config: Config, payload_bytes: Bytes) -> ProcessorResult {
- #[allow(clippy::useless_conversion)]
- let mut bytes: Vec<u8> = payload_bytes.into();
- let payload = Payload::make(&mut bytes);
- print_debug!("{:?}", payload);
-
- make_processor_result(config, payload)
-}
-
-fn make_processor_result(config: Config, payload: Payload) -> ProcessorResult {
- let min_timestamp = payload
- .data_packages
- .iter()
- .enumerate()
- .map(|(index, dp)| config.validate_timestamp(index, dp.timestamp))
- .min()
- .unwrap();
-
- let values = aggregate_values(config, payload.data_packages);
-
- print_debug!("{} {:?}", min_timestamp, values);
-
- ProcessorResult {
- values,
- min_timestamp,
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- processor::make_processor_result,
- processor_result::ProcessorResult,
- test_helpers::{
- BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- },
- helpers::iter_into::IterInto,
- protocol::{data_package::DataPackage, payload::Payload},
- };
-
- #[test]
- fn test_make_processor_result() {
- let data_packages = vec![
- DataPackage::test(
- ETH,
- 11,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 5).into(),
- ),
- DataPackage::test(
- ETH,
- 13,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP + 3).into(),
- ),
- DataPackage::test(
- BTC,
- 32,
- TEST_SIGNER_ADDRESS_2,
- (TEST_BLOCK_TIMESTAMP - 2).into(),
- ),
- DataPackage::test(
- BTC,
- 31,
- TEST_SIGNER_ADDRESS_1,
- (TEST_BLOCK_TIMESTAMP + 400).into(),
- ),
- ];
-
- let result = make_processor_result(Config::test(), Payload { data_packages });
-
- assert_eq!(
- result,
- ProcessorResult {
- min_timestamp: TEST_BLOCK_TIMESTAMP - 2,
- values: vec![12u8, 31].iter_into()
- }
- );
- }
-}
-
use crate::network::specific::U256;
-
-/// Represents the result of processing the RedStone payload.
-///
-/// This structure is used to encapsulate the outcome of a RedStone payload processing operation,
-/// particularly focusing on time-sensitive data and its associated values, according to the `Config`.
-#[derive(Debug, Eq, PartialEq)]
-pub struct ProcessorResult {
- /// The minimum timestamp encountered during processing.
- ///
- /// This field captures the earliest time point (in milliseconds since the Unix epoch)
- /// among the processed data packages, indicating the starting boundary of the dataset's time range.
- pub min_timestamp: u64,
-
- /// A collection of values processed during the operation.
- ///
- /// Each element in this vector represents a processed value corresponding
- /// to the passed data_feed item in the `Config`.
- pub values: Vec<U256>,
-}
-
-impl From<ProcessorResult> for (u64, Vec<U256>) {
- fn from(result: ProcessorResult) -> Self {
- (result.min_timestamp, result.values)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -
use crate::{
- core::config::Config,
- network::{
- assert::Assert,
- error::Error::{InsufficientSignerCount, TimestampTooFuture, TimestampTooOld},
- specific::U256,
- },
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- utils::filter::FilterSome,
-};
-
-/// A trait defining validation operations for data feeds and signers.
-///
-/// This trait specifies methods for validating aspects of data feeds and signers within a system that
-/// requires data integrity and authenticity checks. Implementations of this trait are responsible for
-/// defining the logic behind each validation step, ensuring that data conforms to expected rules and
-/// conditions.
-pub(crate) trait Validator {
- /// Retrieves the index of a given data feed.
- ///
- /// This method takes a `feed_id` representing the unique identifier of a data feed and
- /// returns an `Option<usize>` indicating the index of the feed within a collection of feeds.
- /// If the feed does not exist, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `feed_id`: `U256` - The unique identifier of the data feed.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the feed if it exists, or `None` if it does not.
- fn feed_index(&self, feed_id: U256) -> Option<usize>;
-
- /// Retrieves the index of a given signer.
- ///
- /// This method accepts a signer identifier in the form of a byte slice and returns an
- /// `Option<usize>` indicating the signer's index within a collection of signers. If the signer
- /// is not found, `None` is returned.
- ///
- /// # Arguments
- ///
- /// * `signer`: `&[u8]` - A byte slice representing the signer's identifier.
- ///
- /// # Returns
- ///
- /// * `Option<usize>` - The index of the signer if found, or `None` if not found.
- fn signer_index(&self, signer: &[u8]) -> Option<usize>;
-
- /// Validates the signer count threshold for a given index within a set of values.
- ///
- /// This method is responsible for ensuring that the number of valid signers meets or exceeds
- /// a specified threshold necessary for a set of data values to be considered valid. It returns
- /// a vector of `U256` if the values pass the validation, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value being validated.
- /// * `values`: `&[Option<U256>]` - A slice of optional `U256` values associated with the data.
- ///
- /// # Returns
- ///
- /// * `Vec<U256>` - A vector of `U256` values that meet the validation criteria.
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256>;
-
- /// Validates the timestamp for a given index.
- ///
- /// This method checks whether a timestamp associated with a data value at a given index
- /// meets specific conditions (e.g., being within an acceptable time range). It returns
- /// the validated timestamp if it's valid, to be processed in other steps.
- ///
- /// # Arguments
- ///
- /// * `index`: `usize` - The index of the data value whose timestamp is being validated.
- /// * `timestamp`: `u64` - The timestamp to be validated.
- ///
- /// # Returns
- ///
- /// * `u64` - The validated timestamp.
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64;
-}
-
-impl Validator for Config {
- #[inline]
- fn feed_index(&self, feed_id: U256) -> Option<usize> {
- self.feed_ids.iter().position(|&elt| elt == feed_id)
- }
-
- #[inline]
- fn signer_index(&self, signer: &[u8]) -> Option<usize> {
- self.signers
- .iter()
- .position(|elt| elt.to_ascii_lowercase() == signer.to_ascii_lowercase())
- }
-
- #[inline]
- fn validate_signer_count_threshold(&self, index: usize, values: &[Option<U256>]) -> Vec<U256> {
- values.filter_some().assert_or_revert(
- |x| (*x).len() >= self.signer_count_threshold.into(),
- #[allow(clippy::useless_conversion)]
- |val| InsufficientSignerCount(index, val.len(), self.feed_ids[index]),
- )
- }
-
- #[inline]
- fn validate_timestamp(&self, index: usize, timestamp: u64) -> u64 {
- timestamp.assert_or_revert(
- |&x| x + MAX_TIMESTAMP_DELAY_MS >= self.block_timestamp,
- |timestamp| TimestampTooOld(index, *timestamp),
- );
-
- timestamp.assert_or_revert(
- |&x| x <= self.block_timestamp + MAX_TIMESTAMP_AHEAD_MS,
- |timestamp| TimestampTooFuture(index, *timestamp),
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- core::{
- config::Config,
- test_helpers::{
- AVAX, BTC, ETH, TEST_BLOCK_TIMESTAMP, TEST_SIGNER_ADDRESS_1, TEST_SIGNER_ADDRESS_2,
- },
- validator::Validator,
- },
- helpers::{
- hex::{hex_to_bytes, make_feed_id},
- iter_into::{IterInto, IterIntoOpt, OptIterIntoOpt},
- },
- network::specific::U256,
- protocol::constants::{MAX_TIMESTAMP_AHEAD_MS, MAX_TIMESTAMP_DELAY_MS},
- };
- use itertools::Itertools;
-
- #[test]
- fn test_feed_index() {
- let config = Config::test();
-
- let eth_index = config.feed_index(make_feed_id(ETH));
- assert_eq!(eth_index, 0.into());
-
- let eth_index = config.feed_index(make_feed_id("778680")); //eth
- assert_eq!(eth_index, None);
-
- let btc_index = config.feed_index(make_feed_id(BTC));
- assert_eq!(btc_index, 1.into());
-
- let avax_index = config.feed_index(make_feed_id(AVAX));
- assert_eq!(avax_index, None);
- }
-
- #[test]
- fn test_signer_index() {
- let config = Config::test();
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.into()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_1.to_uppercase()));
- assert_eq!(index, 0.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.into()));
- assert_eq!(index, 1.into());
-
- let index = config.signer_index(&hex_to_bytes(TEST_SIGNER_ADDRESS_2.replace('0', "1")));
- assert_eq!(index, None);
- }
-
- #[test]
- fn test_validate_timestamp() {
- let config = Config::test();
-
- config.validate_timestamp(0, TEST_BLOCK_TIMESTAMP);
- config.validate_timestamp(1, TEST_BLOCK_TIMESTAMP + 60000);
- config.validate_timestamp(2, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS);
- config.validate_timestamp(3, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS);
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP - 60000);
- }
-
- #[should_panic(expected = "Timestamp 2000000180001 is too future for #0")]
- #[test]
- fn test_validate_timestamp_too_future() {
- Config::test().validate_timestamp(0, TEST_BLOCK_TIMESTAMP + MAX_TIMESTAMP_AHEAD_MS + 1);
- }
-
- #[should_panic(expected = "Timestamp 1999999099999 is too old for #1")]
- #[test]
- fn test_validate_timestamp_too_old() {
- Config::test().validate_timestamp(1, TEST_BLOCK_TIMESTAMP - MAX_TIMESTAMP_DELAY_MS - 1);
- }
-
- #[should_panic(expected = "Timestamp 0 is too old for #2")]
- #[test]
- fn test_validate_timestamp_zero() {
- Config::test().validate_timestamp(2, 0);
- }
-
- #[should_panic(expected = "Timestamp 4000000000000 is too future for #3")]
- #[test]
- fn test_validate_timestamp_big() {
- Config::test().validate_timestamp(3, TEST_BLOCK_TIMESTAMP + TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Timestamp 2000000000000 is too future for #4")]
- #[test]
- fn test_validate_timestamp_no_block_timestamp() {
- let mut config = Config::test();
-
- config.block_timestamp = 0;
- config.validate_timestamp(4, TEST_BLOCK_TIMESTAMP);
- }
-
- #[should_panic(expected = "Insufficient signer count 0 for #0 (ETH)")]
- #[test]
- fn test_validate_signer_count_threshold_empty_list() {
- Config::test().validate_signer_count_threshold(0, vec![].as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_shorter_list() {
- Config::test().validate_signer_count_threshold(1, vec![1u8].iter_into_opt().as_slice());
- }
-
- #[should_panic(expected = "Insufficient signer count 1 for #1 (BTC)")]
- #[test]
- fn test_validate_signer_count_threshold_list_with_nones() {
- Config::test().validate_signer_count_threshold(
- 1,
- vec![None, 1u8.into(), None].opt_iter_into_opt().as_slice(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_size() {
- validate_with_all_permutations(vec![1u8, 2].iter_into_opt(), vec![1u8, 2].iter_into());
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_exact_signer_count() {
- validate_with_all_permutations(
- vec![None, 1u8.into(), None, 2.into()].opt_iter_into_opt(),
- vec![1u8, 2].iter_into(),
- );
- }
-
- #[test]
- fn test_validate_signer_count_threshold_with_larger_size() {
- validate_with_all_permutations(
- vec![
- 1u8.into(),
- None,
- None,
- 2.into(),
- 3.into(),
- None,
- 4.into(),
- None,
- ]
- .opt_iter_into_opt(),
- vec![1u8, 2, 3, 4].iter_into(),
- );
- }
-
- fn validate_with_all_permutations(numbers: Vec<Option<U256>>, expected_value: Vec<U256>) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
- let mut config = Config::test();
-
- let result = config.validate_signer_count_threshold(0, &numbers);
- assert_eq!(result, expected_value);
-
- for threshold in 0..expected_value.len() + 1 {
- config.signer_count_threshold = threshold as u8;
-
- for (index, perm) in perms.iter().enumerate() {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- let result =
- config.validate_signer_count_threshold(index % config.feed_ids.len(), &p);
- assert_eq!(result.len(), expected_value.len());
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -
use sha3::{Digest, Keccak256};
-
-pub fn keccak256(data: &[u8]) -> Box<[u8]> {
- Keccak256::new_with_prefix(data)
- .finalize()
- .as_slice()
- .into()
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{crypto::keccak256::keccak256, helpers::hex::hex_to_bytes};
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const EMPTY_MESSAGE_HASH: &str =
- "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
-
- #[test]
- fn test_keccak256() {
- let hash = keccak256(hex_to_bytes(MESSAGE.into()).as_slice());
-
- assert_eq!(hash.as_ref(), hex_to_bytes(MESSAGE_HASH.into()).as_slice());
- }
-
- #[test]
- fn test_keccak256_empty() {
- let hash = keccak256(vec![].as_slice());
-
- assert_eq!(
- hash.as_ref(),
- hex_to_bytes(EMPTY_MESSAGE_HASH.into()).as_slice()
- );
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -
use crate::crypto::{keccak256, recover::crypto256::recover_public_key};
-
-pub fn recover_address(message: Vec<u8>, signature: Vec<u8>) -> Vec<u8> {
- let recovery_byte = signature[64]; // 65-byte representation
- let msg_hash = keccak256::keccak256(message.as_slice());
- let key = recover_public_key(
- msg_hash,
- &signature[..64],
- recovery_byte - (if recovery_byte >= 27 { 27 } else { 0 }),
- );
- let key_hash = keccak256::keccak256(&key[1..]); // skip first uncompressed-key byte
-
- key_hash[12..].into() // last 20 bytes
-}
-
-#[cfg(feature = "crypto_secp256k1")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use secp256k1::{ecdsa::RecoverableSignature, Message, Secp256k1 as Secp256k1Curve};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let msg = Message::from_digest_slice(message_hash.as_ref())
- .unwrap_or_revert(|_| Error::CryptographicError(message_hash.len()));
-
- let recovery_id = secp256k1::ecdsa::RecoveryId::from_i32(recovery_byte.into())
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let sig: RecoverableSignature =
- RecoverableSignature::from_compact(signature_bytes, recovery_id)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let public_key = Secp256k1Curve::new().recover_ecdsa(&msg, &sig);
-
- public_key.unwrap().serialize_uncompressed().into()
- }
-}
-
-#[cfg(feature = "crypto_k256")]
-pub(crate) mod crypto256 {
- use crate::network::{assert::Unwrap, error::Error};
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
-
- pub(crate) fn recover_public_key(
- message_hash: Box<[u8]>,
- signature_bytes: &[u8],
- recovery_byte: u8,
- ) -> Box<[u8]> {
- let recovery_id = RecoveryId::from_byte(recovery_byte)
- .unwrap_or_revert(|_| Error::CryptographicError(recovery_byte.into()));
-
- let signature = Signature::try_from(signature_bytes)
- .unwrap_or_revert(|_| Error::CryptographicError(signature_bytes.len()));
-
- let recovered_key =
- VerifyingKey::recover_from_prehash(message_hash.as_ref(), &signature, recovery_id)
- .map(|key| key.to_encoded_point(false).to_bytes());
-
- recovered_key.unwrap()
- }
-}
-
-#[cfg(all(not(feature = "crypto_k256"), not(feature = "crypto_secp256k1")))]
-pub(crate) mod crypto256 {
- pub(crate) fn recover_public_key(
- _message_hash: Box<[u8]>,
- _signature_bytes: &[u8],
- _recovery_byte: u8,
- ) -> Box<[u8]> {
- panic!("Not implemented!")
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- crypto::recover::{crypto256::recover_public_key, recover_address},
- helpers::hex::hex_to_bytes,
- };
-
- const MESSAGE: &str = "415641580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d394303d018d79bf0ba000000020000001";
- const MESSAGE_HASH: &str = "f0805644755393876d0e917e553f0c206f8bc68b7ebfe73a79d2a9e7f5a4cea6";
- const SIG_V27: &str = "475195641dae43318e194c3d9e5fc308773d6fdf5e197e02644dfd9ca3d19e3e2bd7d8656428f7f02e658a16b8f83722169c57126cc50bec8fad188b1bac6d19";
- const SIG_V28: &str = "c88242d22d88252c845b946c9957dbf3c7d59a3b69ecba2898198869f9f146ff268c3e47a11dbb05cc5198aadd659881817a59ee37e088d3253f4695927428c1";
- const PUBLIC_KEY_V27: &str =
- "04f5f035588502146774d0ccfd62ee5bf1d7f1dbb96aae33a79765c636b8ec75a36f5121931b5cc37215a7d4280c5700ca92daaaf93c32b06ca9f98b1f4ece624e";
- const PUBLIC_KEY_V28: &str =
- "04626f2ad2cfb0b41a24276d78de8959bcf45fc5e80804416e660aab2089d15e98206526e639ee19d17c8f9ae0ce3a6ff1a8ea4ab773d0fb4214e08aad7ba978c8";
- const ADDRESS_V27: &str = "2c59617248994D12816EE1Fa77CE0a64eEB456BF";
- const ADDRESS_V28: &str = "12470f7aBA85c8b81D63137DD5925D6EE114952b";
-
- #[test]
- fn test_recover_public_key_v27() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V27), 0);
-
- assert_eq!(u8_box(PUBLIC_KEY_V27), public_key);
- }
-
- #[test]
- fn test_recover_public_key_v28() {
- let public_key = recover_public_key(u8_box(MESSAGE_HASH), &u8_box(SIG_V28), 1);
-
- assert_eq!(u8_box(PUBLIC_KEY_V28), public_key);
- }
-
- #[test]
- fn test_recover_address_1b() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V27.to_owned() + "1b"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V27.into()), address);
- }
-
- #[test]
- fn test_recover_address_1c() {
- let address = recover_address(
- hex_to_bytes(MESSAGE.into()),
- hex_to_bytes(SIG_V28.to_owned() + "1c"),
- );
-
- assert_eq!(hex_to_bytes(ADDRESS_V28.into()), address);
- }
-
- fn u8_box(str: &str) -> Box<[u8]> {
- hex_to_bytes(str.into()).as_slice().into()
- }
-}
-
//! # RedStone
-//!
-//! `redstone` is a collection of utilities to make deserializing&decrypting RedStone payload.
-//! It includes a pure Rust implementation, along with extensions for certain networks.
-//!
-//! Different crypto-mechanisms are easily injectable.
-//! The current implementation contains `secp256k1`- and `k256`-based variants.
-
-pub mod core;
-mod crypto;
-pub mod network;
-mod protocol;
-mod utils;
-
-#[cfg(feature = "helpers")]
-pub mod helpers;
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -
extern crate alloc;
-
-use crate::network::specific::U256;
-use alloc::{format, string::String};
-
-pub trait AsHexStr {
- fn as_hex_str(&self) -> String;
-}
-
-impl AsHexStr for &[u8] {
- #[allow(clippy::format_collect)]
- fn as_hex_str(&self) -> String {
- self.iter().map(|byte| format!("{:02x}", byte)).collect()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsHexStr for casper_types::bytesrepr::Bytes {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- format!("{:X}", self)
- }
-}
-
-#[cfg(feature = "network_radix")]
-impl AsHexStr for U256 {
- fn as_hex_str(&self) -> String {
- let digits = self.to_digits();
- let mut result = String::new();
- for &part in &digits {
- if result.is_empty() || part != 0u64 {
- result.push_str(&format!("{:02X}", part));
- }
- }
- result
- }
-}
-
-impl AsHexStr for Vec<u8> {
- fn as_hex_str(&self) -> String {
- self.as_slice().as_hex_str()
- }
-}
-
-impl AsHexStr for Box<[u8]> {
- fn as_hex_str(&self) -> String {
- self.as_ref().as_hex_str()
- }
-}
-
-pub trait AsAsciiStr {
- fn as_ascii_str(&self) -> String;
-}
-
-impl AsAsciiStr for &[u8] {
- fn as_ascii_str(&self) -> String {
- self.iter().map(|&code| code as char).collect()
- }
-}
-
-impl AsAsciiStr for Vec<u8> {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-#[cfg(feature = "network_casper")]
-impl AsAsciiStr for casper_types::bytesrepr::Bytes {
- fn as_ascii_str(&self) -> String {
- self.as_slice().as_ascii_str()
- }
-}
-
-impl AsAsciiStr for U256 {
- fn as_ascii_str(&self) -> String {
- let hex_string = self.as_hex_str();
- let bytes = (0..hex_string.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&hex_string[i..i + 2], 16))
- .collect::<Result<Vec<u8>, _>>()
- .unwrap();
-
- bytes.as_ascii_str()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
- };
-
- const ETH: u32 = 4543560u32;
-
- #[test]
- fn test_as_hex_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_hex_str();
-
- assert_eq!(result, "455448");
- }
-
- #[test]
- fn test_as_ascii_str() {
- let u256 = U256::from(ETH);
- let result = u256.as_ascii_str();
-
- assert_eq!(result, "ETH");
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -
use crate::{
- network::{error::Error, specific::revert},
- print_debug,
-};
-use std::fmt::Debug;
-
-pub trait Assert<F> {
- fn assert_or_revert<E: Fn(&Self) -> Error>(self, check: F, error: E) -> Self;
-}
-
-impl<T, F> Assert<F> for T
-where
- T: Debug,
- F: Fn(&Self) -> bool,
-{
- fn assert_or_revert<E: FnOnce(&Self) -> Error>(self, check: F, error: E) -> Self {
- assert_or_revert(self, check, error)
- }
-}
-
-#[inline]
-fn assert_or_revert<F, T, E: FnOnce(&T) -> Error>(arg: T, check: F, error: E) -> T
-where
- F: Fn(&T) -> bool,
- T: Debug,
-{
- assert_or_revert_bool_with(check(&arg), || error(&arg));
-
- arg
-}
-
-#[inline]
-fn assert_or_revert_bool_with<E: FnOnce() -> Error>(check: bool, error: E) {
- if check {
- return;
- }
-
- let error = error();
- print_debug!("REVERT({}) - {}!", &error.code(), error);
- revert(error);
-}
-
-pub trait Unwrap<R> {
- type ErrorArg;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> R;
-}
-
-impl<T> Unwrap<T> for Option<T>
-where
- T: Debug,
-{
- type ErrorArg = ();
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(self, |arg| arg.is_some(), |_| error(&())).unwrap()
- }
-}
-
-impl<T, Err> Unwrap<T> for Result<T, Err>
-where
- T: Debug,
- Err: Debug,
-{
- type ErrorArg = Err;
-
- fn unwrap_or_revert<E: Fn(&Self::ErrorArg) -> Error>(self, error: E) -> T {
- assert_or_revert(
- self,
- |arg| arg.is_ok(),
- |e| error(e.as_ref().err().unwrap()),
- )
- .unwrap()
- }
-}
-
-#[cfg(test)]
-mod assert_or_revert_tests {
- use crate::network::{
- assert::{assert_or_revert_bool_with, Assert},
- error::Error,
- };
-
- #[test]
- fn test_assert_or_revert_bool_with_true() {
- assert_or_revert_bool_with(true, || Error::ArrayIsEmpty);
- }
-
- #[should_panic(expected = "Array is empty")]
- #[test]
- fn test_assert_or_revert_bool_with_false() {
- assert_or_revert_bool_with(false, || Error::ArrayIsEmpty);
- }
-
- #[test]
- fn test_assert_or_revert_correct() {
- 5.assert_or_revert(|&x| x == 5, |&size| Error::SizeNotSupported(size));
- }
-
- #[should_panic(expected = "Size not supported: 5")]
- #[test]
- fn test_assert_or_revert_wrong() {
- 5.assert_or_revert(|&x| x < 5, |&size| Error::SizeNotSupported(size));
- }
-}
-
-#[cfg(test)]
-mod unwrap_or_revert_tests {
- use crate::network::{assert::Unwrap, error::Error};
-
- #[test]
- fn test_unwrap_or_revert_some() {
- let result = Some(543).unwrap_or_revert(|_| Error::CryptographicError(333));
-
- assert_eq!(result, 543);
- }
-
- #[should_panic(expected = "Cryptographic Error: 333")]
- #[test]
- fn test_unwrap_or_revert_none() {
- (Option::<u64>::None).unwrap_or_revert(|_| Error::CryptographicError(333));
- }
-
- #[test]
- fn test_unwrap_or_revert_ok() {
- let result = Ok(256).unwrap_or_revert(|_: &Error| Error::CryptographicError(333));
-
- assert_eq!(result, 256);
- }
-
- #[should_panic(expected = "Cryptographic Error: 567")]
- #[test]
- fn test_unwrap_or_revert_err() {
- Result::<&[u8], Error>::Err(Error::CryptographicError(567)).unwrap_or_revert(|e| e.clone());
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod error;
-mod from_bytes_repr;
-
-pub struct Casper;
-
-impl NetworkSpecific for Casper {
- type BytesRepr = casper_types::bytesrepr::Bytes;
- type ValueRepr = casper_types::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- casper_contract::contract_api::runtime::print(&_text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- casper_contract::contract_api::runtime::revert(error)
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -
use crate::network::{
- as_str::{AsAsciiStr, AsHexStr},
- specific::U256,
-};
-use std::fmt::{Debug, Display, Formatter};
-
-pub trait ContractErrorContent: Debug {
- fn code(&self) -> u8;
- fn message(&self) -> String;
-}
-
-/// Errors that can be encountered in the deserializing&decrypting the RedStone payload or just contract execution process.
-///
-/// These errors include issues with contract logic, data types,
-/// cryptographic operations, and conditions specific to the requirements.
-#[derive(Debug)]
-pub enum Error {
- /// Represents errors that arise from the contract itself.
- ///
- /// This variant is used for encapsulating errors that are specific to the contract's logic
- /// or execution conditions that aren't covered by more specific error types.
- ContractError(Box<dyn ContractErrorContent>),
-
- /// Indicates an overflow error with `U256` numbers.
- ///
- /// Used when operations on `U256` numbers exceed their maximum value, potentially leading
- /// to incorrect calculations or state.
- NumberOverflow(U256),
-
- /// Used when an expected non-empty array or vector is found to be empty.
- ///
- /// This could occur in scenarios where the contract logic requires a non-empty collection
- /// of items for the correct operation, for example, during aggregating the values.
- ArrayIsEmpty,
-
- /// Represents errors related to cryptographic operations.
- ///
- /// This includes failures in signature verification, hashing, or other cryptographic
- /// processes, with the usize indicating the position or identifier of the failed operation.
- CryptographicError(usize),
-
- /// Signifies that an unsupported size was encountered.
- ///
- /// This could be used when a data structure or input does not meet the expected size
- /// requirements for processing.
- SizeNotSupported(usize),
-
- /// Indicates that the marker bytes for RedStone are incorrect.
- ///
- /// This error is specific to scenarios where marker or identifier bytes do not match
- /// expected values, potentially indicating corrupted or tampered data.
- WrongRedStoneMarker(Vec<u8>),
-
- /// Used when there is leftover data in a payload that should have been empty.
- ///
- /// This could indicate an error in data parsing or that additional, unexpected data
- /// was included in a message or transaction.
- NonEmptyPayloadRemainder(Vec<u8>),
-
- /// Indicates that the number of signers does not meet the required threshold.
- ///
- /// This variant includes the current number of signers, the required threshold, and
- /// potentially a feed_id related to the operation that failed due to insufficient signers.
- InsufficientSignerCount(usize, usize, U256),
-
- /// Used when a timestamp is older than allowed by the processor logic.
- ///
- /// Includes the position or identifier of the timestamp and the threshold value,
- /// indicating that the provided timestamp is too far in the past.
- TimestampTooOld(usize, u64),
-
- /// Indicates that a timestamp is further in the future than allowed.
- ///
- /// Similar to `TimestampTooOld`, but for future timestamps exceeding the contract's
- /// acceptance window.
- TimestampTooFuture(usize, u64),
-
- /// Represents errors that need to clone `ContractErrorContent`, which is not supported by default.
- ///
- /// This variant allows for the manual duplication of contract error information, including
- /// an error code and a descriptive message.
- ClonedContractError(u8, String),
-}
-
-impl Error {
- pub fn contract_error<T: ContractErrorContent + 'static>(value: T) -> Error {
- Error::ContractError(Box::new(value))
- }
-
- pub(crate) fn code(&self) -> u16 {
- match self {
- Error::ContractError(boxed) => boxed.code() as u16,
- Error::NumberOverflow(_) => 509,
- Error::ArrayIsEmpty => 510,
- Error::WrongRedStoneMarker(_) => 511,
- Error::NonEmptyPayloadRemainder(_) => 512,
- Error::InsufficientSignerCount(data_package_index, value, _) => {
- (2000 + data_package_index * 10 + value) as u16
- }
- Error::SizeNotSupported(size) => 600 + *size as u16,
- Error::CryptographicError(size) => 700 + *size as u16,
- Error::TimestampTooOld(data_package_index, _) => 1000 + *data_package_index as u16,
- Error::TimestampTooFuture(data_package_index, _) => 1050 + *data_package_index as u16,
- Error::ClonedContractError(code, _) => *code as u16,
- }
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- Error::ContractError(boxed) => write!(f, "Contract error: {}", boxed.message()),
- Error::NumberOverflow(number) => write!(f, "Number overflow: {}", number),
- Error::ArrayIsEmpty => write!(f, "Array is empty"),
- Error::CryptographicError(size) => write!(f, "Cryptographic Error: {}", size),
- Error::SizeNotSupported(size) => write!(f, "Size not supported: {}", size),
- Error::WrongRedStoneMarker(bytes) => {
- write!(f, "Wrong RedStone marker: {}", bytes.as_hex_str())
- }
- Error::NonEmptyPayloadRemainder(bytes) => {
- write!(f, "Non empty payload remainder: {}", bytes.as_hex_str())
- }
- Error::InsufficientSignerCount(data_package_index, value, feed_id) => write!(
- f,
- "Insufficient signer count {} for #{} ({})",
- value,
- data_package_index,
- feed_id.as_ascii_str()
- ),
- Error::TimestampTooOld(data_package_index, value) => {
- write!(
- f,
- "Timestamp {} is too old for #{}",
- value, data_package_index
- )
- }
- Error::TimestampTooFuture(data_package_index, value) => write!(
- f,
- "Timestamp {} is too future for #{}",
- value, data_package_index
- ),
- Error::ClonedContractError(_, message) => {
- write!(f, "(Cloned) Contract error: {}", message)
- }
- }
- }
-}
-
-impl Clone for Error {
- fn clone(&self) -> Self {
- match self {
- Error::ContractError(content) => {
- Error::ClonedContractError(content.code(), content.message())
- }
- Error::NumberOverflow(value) => Error::NumberOverflow(*value),
- Error::ArrayIsEmpty => Error::ArrayIsEmpty,
- Error::CryptographicError(size) => Error::CryptographicError(*size),
- Error::SizeNotSupported(size) => Error::SizeNotSupported(*size),
- Error::WrongRedStoneMarker(bytes) => Error::WrongRedStoneMarker(bytes.clone()),
- Error::NonEmptyPayloadRemainder(bytes) => {
- Error::NonEmptyPayloadRemainder(bytes.clone())
- }
- Error::InsufficientSignerCount(count, needed, bytes) => {
- Error::InsufficientSignerCount(*count, *needed, *bytes)
- }
- Error::TimestampTooOld(index, timestamp) => Error::TimestampTooOld(*index, *timestamp),
- Error::TimestampTooFuture(index, timestamp) => {
- Error::TimestampTooFuture(*index, *timestamp)
- }
- Error::ClonedContractError(code, message) => {
- Error::ClonedContractError(*code, message.as_str().into())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -
use crate::network::specific::Bytes;
-
-pub trait Flattened<T> {
- fn flattened(&self) -> T;
-}
-
-impl Flattened<Bytes> for Vec<Bytes> {
- fn flattened(&self) -> Bytes {
- #[allow(clippy::useless_conversion)]
- self.iter().flatten().copied().collect::<Vec<_>>().into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{flattened::Flattened, specific::Bytes};
-
- #[test]
- fn test_bytes_flattened() {
- #[allow(clippy::useless_conversion)]
- let bytes: Vec<Bytes> = vec![
- vec![1u8, 2, 3].into(),
- vec![4u8].into(),
- vec![].into(),
- vec![5, 6, 7].into(),
- ];
-
- let result: Bytes = bytes.flattened();
-
- #[allow(clippy::useless_conversion)]
- let expected_result: Bytes = vec![1u8, 2, 3, 4, 5, 6, 7].into();
-
- assert_eq!(result, expected_result);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -
use crate::network::specific::VALUE_SIZE;
-
-pub trait FromBytesRepr<T> {
- fn from_bytes_repr(bytes: T) -> Self;
-}
-
-pub trait Sanitized {
- fn sanitized(self) -> Self;
-}
-
-impl Sanitized for Vec<u8> {
- fn sanitized(self) -> Self {
- if self.len() <= VALUE_SIZE {
- return self;
- }
-
- let index = self.len().max(VALUE_SIZE) - VALUE_SIZE;
- let remainder = &self[0..index];
-
- if remainder != vec![0; index] {
- panic!("Number to big: {:?} digits", self.len())
- }
-
- self[index..].into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- };
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[test]
- fn test_from_bytes_repr_single() {
- let vec = vec![1];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(1u32));
- }
-
- #[test]
- fn test_from_bytes_repr_double() {
- let vec = vec![1, 2];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(258u32));
- }
-
- #[test]
- fn test_from_bytes_repr_simple() {
- let vec = vec![1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[test]
- fn test_from_bytes_repr_bigger() {
- let vec = vec![101, 202, 255];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(6671103u32));
- }
-
- #[test]
- fn test_from_bytes_repr_empty() {
- let result = U256::from_bytes_repr(Vec::new());
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[test]
- fn test_from_bytes_repr_trailing_zeroes() {
- let vec = vec![1, 2, 3, 0];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(16909056u32));
- }
-
- #[test]
- fn test_from_bytes_repr_leading_zeroes() {
- let vec = vec![0, 1, 2, 3];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(66051u32));
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_max() {
- let vec = vec![255; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-
- #[test]
- fn test_from_bytes_repr_min() {
- let vec = vec![0; VALUE_SIZE];
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::from(0u8));
- }
-
- #[should_panic(expected = "Number to big")]
- #[test]
- fn test_from_bytes_repr_too_long() {
- let x = VALUE_SIZE as u8 + 1;
- let vec = (1..=x).collect();
-
- U256::from_bytes_repr(vec);
- }
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_from_bytes_repr_too_long_but_zeroes() {
- let mut vec = vec![255; VALUE_SIZE + 1];
- vec[0] = 0;
- let result = U256::from_bytes_repr(vec);
-
- assert_eq!(result, U256::max_value());
- }
-}
-
pub mod as_str;
-pub mod assert;
-pub mod error;
-pub mod from_bytes_repr;
-pub mod print_debug;
-pub mod specific;
-
-#[cfg(feature = "network_casper")]
-pub mod casper;
-
-#[cfg(feature = "network_casper")]
-pub type _Network = casper::Casper;
-
-#[cfg(feature = "network_radix")]
-pub mod radix;
-
-#[cfg(feature = "network_radix")]
-pub type _Network = radix::Radix;
-
-pub mod flattened;
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-mod pure;
-
-#[cfg(all(not(feature = "network_casper"), not(feature = "network_radix")))]
-pub type _Network = pure::Std;
-
extern crate alloc;
-
-#[macro_export]
-macro_rules! print_debug {
- ($fmt:expr) => {
- $crate::network::specific::print(format!($fmt))
- };
- ($fmt:expr, $($args:tt)*) => {
- $crate::network::specific::print(format!($fmt, $($args)*))
- };
-}
-
-#[macro_export]
-macro_rules! print_and_panic {
- ($fmt:expr) => {{
- $crate::print_debug!($fmt);
- panic!($fmt)
- }};
- ($fmt:expr, $($args:tt)*) => {{
- $crate::print_debug!($fmt, $($args)*);
- panic!($fmt, $($args)*)
- }};
-}
-
use crate::network::{error::Error, specific::NetworkSpecific};
-use primitive_types::U256;
-use std::eprintln;
-
-mod from_bytes_repr;
-
-pub struct Std;
-
-impl NetworkSpecific for Std {
- type BytesRepr = Vec<u8>;
- type ValueRepr = U256;
- type _Self = Std;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(text: String) {
- eprintln!("{}", text)
- }
-
- fn revert(error: Error) -> ! {
- panic!("{}", error)
- }
-}
-
use crate::network::{
- from_bytes_repr::{FromBytesRepr, Sanitized},
- specific::U256,
-};
-
-impl FromBytesRepr<Vec<u8>> for U256 {
- fn from_bytes_repr(bytes: Vec<u8>) -> Self {
- match bytes.len() {
- 0 => U256::ZERO,
- 1 => U256::from(bytes[0]),
- _ => {
- // TODO: make it cheaper
- let mut bytes_le = bytes.sanitized();
- bytes_le.reverse();
-
- U256::from_le_bytes(bytes_le.as_slice())
- }
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -
use crate::network::{error::Error, specific::NetworkSpecific};
-
-mod from_bytes_repr;
-pub mod u256_ext;
-
-pub struct Radix;
-
-impl NetworkSpecific for Radix {
- type BytesRepr = Vec<u8>;
- type ValueRepr = radix_common::math::bnum_integer::U256;
- type _Self = Self;
-
- const VALUE_SIZE: usize = 32;
-
- fn print(_text: String) {
- #[cfg(all(not(test), feature = "print_debug"))]
- {
- scrypto::prelude::info!("{}", _text);
- }
-
- #[cfg(test)]
- {
- println!("{}", _text);
- }
- }
-
- fn revert(error: Error) -> ! {
- #[cfg(not(test))]
- {
- scrypto::prelude::Runtime::panic(error.to_string())
- }
-
- #[cfg(test)]
- {
- panic!("{}", error)
- }
- }
-}
-
use crate::network::{_Network, error::Error, from_bytes_repr::FromBytesRepr};
-
-pub trait NetworkSpecific {
- type BytesRepr: From<Vec<u8>> + Into<Vec<u8>>;
- type ValueRepr: FromBytesRepr<Vec<u8>>;
- type _Self;
-
- const VALUE_SIZE: usize;
-
- fn print(_text: String);
- fn revert(error: Error) -> !;
-}
-
-pub(crate) type Network = <_Network as NetworkSpecific>::_Self;
-pub type Bytes = <_Network as NetworkSpecific>::BytesRepr;
-pub type U256 = <_Network as NetworkSpecific>::ValueRepr;
-pub const VALUE_SIZE: usize = <_Network as NetworkSpecific>::VALUE_SIZE;
-
-pub fn print(_text: String) {
- Network::print(_text)
-}
-
-pub fn revert(error: Error) -> ! {
- Network::revert(error)
-}
-
pub(crate) const UNSIGNED_METADATA_BYTE_SIZE_BS: usize = 3;
-pub(crate) const DATA_PACKAGES_COUNT_BS: usize = 2;
-pub(crate) const DATA_POINTS_COUNT_BS: usize = 3;
-pub(crate) const SIGNATURE_BS: usize = 65;
-pub(crate) const DATA_POINT_VALUE_BYTE_SIZE_BS: usize = 4;
-pub(crate) const DATA_FEED_ID_BS: usize = 32;
-pub(crate) const TIMESTAMP_BS: usize = 6;
-pub(crate) const MAX_TIMESTAMP_DELAY_MS: u64 = 15 * 60 * 1000; // 15 minutes in milliseconds
-pub(crate) const MAX_TIMESTAMP_AHEAD_MS: u64 = 3 * 60 * 1000; // 3 minutes in milliseconds
-pub(crate) const REDSTONE_MARKER_BS: usize = 9;
-pub(crate) const REDSTONE_MARKER: [u8; 9] = [0, 0, 2, 237, 87, 1, 30, 0, 0]; // 0x000002ed57011e0000
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -
use crate::{
- crypto::recover::recover_address,
- network::as_str::AsHexStr,
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_point::{trim_data_points, DataPoint},
- },
- utils::trim::Trim,
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPackage {
- pub(crate) signer_address: Vec<u8>,
- pub(crate) timestamp: u64,
- pub(crate) data_points: Vec<DataPoint>,
-}
-
-pub(crate) fn trim_data_packages(payload: &mut Vec<u8>, count: usize) -> Vec<DataPackage> {
- let mut data_packages = Vec::new();
-
- for _ in 0..count {
- let data_package = trim_data_package(payload);
- data_packages.push(data_package);
- }
-
- data_packages
-}
-
-fn trim_data_package(payload: &mut Vec<u8>) -> DataPackage {
- let signature = payload.trim_end(SIGNATURE_BS);
- let mut tmp = payload.clone();
-
- let data_point_count = payload.trim_end(DATA_POINTS_COUNT_BS);
- let value_size = payload.trim_end(DATA_POINT_VALUE_BYTE_SIZE_BS);
- let timestamp = payload.trim_end(TIMESTAMP_BS);
- let size = data_point_count * (value_size + DATA_FEED_ID_BS)
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + DATA_POINTS_COUNT_BS;
-
- let signable_bytes = tmp.trim_end(size);
- let signer_address = recover_address(signable_bytes, signature);
-
- let data_points = trim_data_points(payload, data_point_count, value_size);
-
- DataPackage {
- data_points,
- timestamp,
- signer_address,
- }
-}
-
-impl Debug for DataPackage {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPackage {{\n signer_address: 0x{}, timestamp: {},\n data_points: {:?}\n}}",
- self.signer_address.as_hex_str(),
- self.timestamp,
- self.data_points
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{from_bytes_repr::FromBytesRepr, specific::U256},
- protocol::{
- constants::{
- DATA_FEED_ID_BS, DATA_POINTS_COUNT_BS, DATA_POINT_VALUE_BYTE_SIZE_BS, SIGNATURE_BS,
- TIMESTAMP_BS,
- },
- data_package::{trim_data_package, trim_data_packages, DataPackage},
- data_point::DataPoint,
- },
- };
-
- const DATA_PACKAGE_BYTES_1: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e018d79bf0ba00000002000000151afa8c5c3caf6004b42c0fb17723e524f993b9ecbad3b9bce5ec74930fa436a3660e8edef10e96ee5f222de7ef5787c02ca467c0ec18daa2907b43ac20c63c11c";
- const DATA_PACKAGE_BYTES_2: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cdd851e018d79bf0ba000000020000001473fd9dc72e6814a7de719b403cf4c9eba08934a643fd0666c433b806b31e69904f2226ffd3c8ef75861b11b5e32a1fda4b1458e0da4605a772dfba2a812f3ee1b";
-
- const SIGNER_ADDRESS_1: &str = "1ea62d73edf8ac05dfcea1a34b9796e937a29eff";
- const SIGNER_ADDRESS_2: &str = "109b4a318a4f5ddcbca6349b45f881b4137deafb";
-
- const VALUE_1: u128 = 232141080910;
- const VALUE_2: u128 = 232144078110;
-
- const DATA_PACKAGE_SIZE: usize = 32
- + DATA_FEED_ID_BS
- + DATA_POINT_VALUE_BYTE_SIZE_BS
- + TIMESTAMP_BS
- + SIGNATURE_BS
- + DATA_POINTS_COUNT_BS;
-
- #[test]
- fn test_trim_data_packages() {
- test_trim_data_packages_of(2, "");
- test_trim_data_packages_of(0, "");
- test_trim_data_packages_of(1, "");
- }
-
- #[test]
- fn test_trim_data_packages_with_prefix() {
- let prefix = "da4687f1914a1c";
-
- test_trim_data_packages_of(2, prefix);
- }
-
- #[test]
- fn test_trim_data_packages_single() {
- let mut bytes = hex_to_bytes(DATA_PACKAGE_BYTES_1.into());
- let data_packages = trim_data_packages(&mut bytes, 1);
- assert_eq!(data_packages.len(), 1);
- assert_eq!(bytes, Vec::<u8>::new());
-
- verify_data_package(data_packages[0].clone(), VALUE_1, SIGNER_ADDRESS_1);
- }
-
- fn test_trim_data_packages_of(count: usize, prefix: &str) {
- let input: Vec<u8> =
- hex_to_bytes((prefix.to_owned() + DATA_PACKAGE_BYTES_1) + DATA_PACKAGE_BYTES_2);
- let mut bytes = input.clone();
- let data_packages = trim_data_packages(&mut bytes, count);
-
- assert_eq!(data_packages.len(), count);
- assert_eq!(
- bytes.as_slice(),
- &input[..input.len() - count * DATA_PACKAGE_SIZE]
- );
-
- let values = &[VALUE_2, VALUE_1];
- let signers = &[SIGNER_ADDRESS_2, SIGNER_ADDRESS_1];
-
- for i in 0..count {
- verify_data_package(data_packages[i].clone(), values[i], signers[i]);
- }
- }
-
- #[should_panic(expected = "index out of bounds")]
- #[test]
- fn test_trim_data_packages_bigger_number() {
- test_trim_data_packages_of(3, "");
- }
-
- #[test]
- fn test_trim_data_package() {
- test_trim_data_package_of(DATA_PACKAGE_BYTES_1, VALUE_1, SIGNER_ADDRESS_1);
- test_trim_data_package_of(DATA_PACKAGE_BYTES_2, VALUE_2, SIGNER_ADDRESS_2);
- }
-
- #[test]
- fn test_trim_data_package_with_prefix() {
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_1),
- VALUE_1,
- SIGNER_ADDRESS_1,
- );
- test_trim_data_package_of(
- &("da4687f1914a1c".to_owned() + DATA_PACKAGE_BYTES_2),
- VALUE_2,
- SIGNER_ADDRESS_2,
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_signature_only() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1[(DATA_PACKAGE_BYTES_1.len() - 2 * SIGNATURE_BS)..],
- 0,
- "",
- );
- }
-
- #[should_panic]
- #[test]
- fn test_trim_data_package_shorter() {
- test_trim_data_package_of(
- &DATA_PACKAGE_BYTES_1
- [(DATA_PACKAGE_BYTES_1.len() - 2 * (SIGNATURE_BS + DATA_POINTS_COUNT_BS))..],
- 0,
- "",
- );
- }
-
- fn test_trim_data_package_of(bytes_str: &str, expected_value: u128, signer_address: &str) {
- let mut bytes: Vec<u8> = hex_to_bytes(bytes_str.into());
- let result = trim_data_package(&mut bytes);
- assert_eq!(
- bytes,
- hex_to_bytes(bytes_str[..bytes_str.len() - 2 * (DATA_PACKAGE_SIZE)].into())
- );
-
- verify_data_package(result, expected_value, signer_address);
- }
-
- fn verify_data_package(result: DataPackage, expected_value: u128, signer_address: &str) {
- let data_package = DataPackage {
- data_points: vec![DataPoint {
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_PACKAGE_BYTES_1[..6].into())),
- value: U256::from(expected_value),
- }],
- timestamp: 1707144580000,
- signer_address: hex_to_bytes(signer_address.into()),
- };
-
- assert_eq!(result, data_package);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -
use crate::{
- network::{
- as_str::{AsAsciiStr, AsHexStr},
- assert::Assert,
- error::Error,
- from_bytes_repr::FromBytesRepr,
- specific::U256,
- },
- protocol::constants::DATA_FEED_ID_BS,
- utils::{trim::Trim, trim_zeros::TrimZeros},
-};
-use std::fmt::{Debug, Formatter};
-
-#[derive(Clone, PartialEq, Eq)]
-pub(crate) struct DataPoint {
- pub(crate) feed_id: U256,
- pub(crate) value: U256,
-}
-
-pub(crate) fn trim_data_points(
- payload: &mut Vec<u8>,
- count: usize,
- value_size: usize,
-) -> Vec<DataPoint> {
- count.assert_or_revert(|&count| count == 1, |&count| Error::SizeNotSupported(count));
-
- let mut data_points = Vec::new();
-
- for _ in 0..count {
- let data_point = trim_data_point(payload, value_size);
- data_points.push(data_point);
- }
-
- data_points
-}
-
-fn trim_data_point(payload: &mut Vec<u8>, value_size: usize) -> DataPoint {
- let value = payload.trim_end(value_size);
- let feed_id: Vec<u8> = payload.trim_end(DATA_FEED_ID_BS);
-
- DataPoint {
- value,
- feed_id: U256::from_bytes_repr(feed_id.trim_zeros()),
- }
-}
-
-impl Debug for DataPoint {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "DataPoint {{\n feed_id: {:?} (0x{}), value: {}\n }}",
- self.feed_id.as_ascii_str(),
- self.feed_id.as_hex_str(),
- self.value,
- )
- }
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- network::{
- from_bytes_repr::FromBytesRepr,
- specific::{U256, VALUE_SIZE},
- },
- protocol::{
- constants::DATA_FEED_ID_BS,
- data_point::{trim_data_point, trim_data_points, DataPoint},
- },
- };
- use std::ops::Shr;
-
- const DATA_POINT_BYTES_TAIL: &str = "4554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000360cafc94e";
- const VALUE: u128 = 232141080910;
-
- #[test]
- fn test_trim_data_points() {
- let mut bytes = hex_to_bytes(DATA_POINT_BYTES_TAIL.into());
- let result = trim_data_points(&mut bytes, 1, 32);
-
- assert_eq!(result.len(), 1);
-
- verify_rest_and_result(
- DATA_POINT_BYTES_TAIL,
- 32,
- VALUE.into(),
- bytes,
- result[0].clone(),
- )
- }
-
- #[should_panic(expected = "Size not supported: 0")]
- #[test]
- fn test_trim_zero_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 0, 32);
- }
-
- #[should_panic(expected = "Size not supported: 2")]
- #[test]
- fn test_trim_two_data_points() {
- trim_data_points(&mut hex_to_bytes(DATA_POINT_BYTES_TAIL.into()), 2, 32);
- }
-
- #[test]
- fn test_trim_data_point() {
- test_trim_data_point_of(DATA_POINT_BYTES_TAIL, 32, VALUE.into());
- }
-
- #[test]
- fn test_trim_data_point_with_prefix() {
- test_trim_data_point_of(
- &("a2a812f3ee1b".to_owned() + DATA_POINT_BYTES_TAIL),
- 32,
- VALUE.into(),
- );
- }
-
- #[test]
- fn test_trim_data_point_other_lengths() {
- for i in 1..VALUE_SIZE {
- test_trim_data_point_of(
- &DATA_POINT_BYTES_TAIL[..DATA_POINT_BYTES_TAIL.len() - 2 * i],
- 32 - i,
- U256::from(VALUE).shr(8 * i as u32),
- );
- }
- }
-
- fn test_trim_data_point_of(value: &str, size: usize, expected_value: U256) {
- let mut bytes = hex_to_bytes(value.into());
- let result = trim_data_point(&mut bytes, size);
-
- verify_rest_and_result(value, size, expected_value, bytes, result);
- }
-
- fn verify_rest_and_result(
- value: &str,
- size: usize,
- expected_value: U256,
- rest: Vec<u8>,
- result: DataPoint,
- ) {
- assert_eq!(
- rest,
- hex_to_bytes(value[..value.len() - 2 * (size + DATA_FEED_ID_BS)].into())
- );
-
- let data_point = DataPoint {
- value: expected_value,
- feed_id: U256::from_bytes_repr(hex_to_bytes(DATA_POINT_BYTES_TAIL[..6].to_string())),
- };
-
- assert_eq!(result, data_point);
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
-};
-
-pub fn trim_redstone_marker(payload: &mut Vec<u8>) {
- let marker: Vec<u8> = payload.trim_end(REDSTONE_MARKER_BS);
-
- marker.as_slice().assert_or_revert(
- |&marker| marker == REDSTONE_MARKER,
- |&val| Error::WrongRedStoneMarker(val.into()),
- );
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::hex_to_bytes,
- protocol::{constants::REDSTONE_MARKER_BS, marker::trim_redstone_marker},
- };
-
- const PAYLOAD_TAIL: &str = "1c000f000000000002ed57011e0000";
-
- #[test]
- fn test_trim_redstone_marker() {
- let mut bytes = hex_to_bytes(PAYLOAD_TAIL.into());
- trim_redstone_marker(&mut bytes);
-
- assert_eq!(
- bytes,
- hex_to_bytes(PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2 * REDSTONE_MARKER_BS].into())
- );
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 000002ed57022e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong() {
- trim_redstone_marker(&mut hex_to_bytes(PAYLOAD_TAIL.replace('1', "2")));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 00000002ed57011e00")]
- #[test]
- fn test_trim_redstone_marker_wrong_ending() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[..PAYLOAD_TAIL.len() - 2].into(),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 100002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_wrong_beginning() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL.replace("0000000", "1111111"),
- ));
- }
-
- #[should_panic(expected = "Wrong RedStone marker: 0002ed57011e0000")]
- #[test]
- fn test_trim_redstone_marker_too_short() {
- trim_redstone_marker(&mut hex_to_bytes(
- PAYLOAD_TAIL[PAYLOAD_TAIL.len() - 2 * (REDSTONE_MARKER_BS - 1)..].into(),
- ));
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -
use crate::{
- network::{assert::Assert, error::Error},
- protocol::{
- constants::{DATA_PACKAGES_COUNT_BS, UNSIGNED_METADATA_BYTE_SIZE_BS},
- data_package::{trim_data_packages, DataPackage},
- marker,
- },
- utils::trim::Trim,
-};
-
-#[derive(Clone, Debug)]
-pub(crate) struct Payload {
- pub(crate) data_packages: Vec<DataPackage>,
-}
-
-impl Payload {
- pub(crate) fn make(payload_bytes: &mut Vec<u8>) -> Payload {
- marker::trim_redstone_marker(payload_bytes);
- let payload = trim_payload(payload_bytes);
-
- payload_bytes.assert_or_revert(
- |bytes| bytes.is_empty(),
- |bytes| Error::NonEmptyPayloadRemainder(bytes.as_slice().into()),
- );
-
- payload
- }
-}
-
-fn trim_payload(payload: &mut Vec<u8>) -> Payload {
- let data_package_count = trim_metadata(payload);
- let data_packages = trim_data_packages(payload, data_package_count);
-
- Payload { data_packages }
-}
-
-fn trim_metadata(payload: &mut Vec<u8>) -> usize {
- let unsigned_metadata_size = payload.trim_end(UNSIGNED_METADATA_BYTE_SIZE_BS);
- let _: Vec<u8> = payload.trim_end(unsigned_metadata_size);
-
- payload.trim_end(DATA_PACKAGES_COUNT_BS)
-}
-
-#[cfg(feature = "helpers")]
-#[cfg(test)]
-mod tests {
- use crate::{
- helpers::hex::{hex_to_bytes, read_payload_bytes, read_payload_hex},
- protocol::{
- constants::REDSTONE_MARKER_BS,
- payload::{trim_metadata, trim_payload, Payload},
- },
- };
-
- const PAYLOAD_METADATA_BYTES: &str = "000f000000";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTE: &str = "000f55000001";
- const PAYLOAD_METADATA_WITH_UNSIGNED_BYTES: &str = "000f11223344556677889900aabbccddeeff000010";
-
- #[test]
- fn test_trim_metadata() {
- let prefix = "9e0294371c";
-
- for &bytes_str in &[
- PAYLOAD_METADATA_BYTES,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTE,
- PAYLOAD_METADATA_WITH_UNSIGNED_BYTES,
- ] {
- let mut bytes = hex_to_bytes(prefix.to_owned() + bytes_str);
- let result = trim_metadata(&mut bytes);
-
- assert_eq!(bytes, hex_to_bytes(prefix.into()));
- assert_eq!(result, 15);
- }
- }
-
- #[test]
- fn test_trim_payload() {
- let payload_hex = read_payload_bytes("./sample-data/payload.hex");
-
- let mut bytes = payload_hex[..payload_hex.len() - REDSTONE_MARKER_BS].into();
- let payload = trim_payload(&mut bytes);
-
- assert_eq!(bytes, Vec::<u8>::new());
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[test]
- fn test_make_payload() {
- let mut payload_hex = read_payload_bytes("./sample-data/payload.hex");
- let payload = Payload::make(&mut payload_hex);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-
- #[should_panic(expected = "Non empty payload remainder: 12")]
- #[test]
- fn test_make_payload_with_prefix() {
- let payload_hex = read_payload_hex("./sample-data/payload.hex");
- let mut bytes = hex_to_bytes("12".to_owned() + &payload_hex);
- let payload = Payload::make(&mut bytes);
-
- assert_eq!(payload.data_packages.len(), 15);
- }
-}
-
pub(crate) trait FilterSome<Output> {
- fn filter_some(&self) -> Output;
-}
-
-impl<T: Copy> FilterSome<Vec<T>> for [Option<T>] {
- fn filter_some(&self) -> Vec<T> {
- self.iter().filter_map(|&opt| opt).collect()
- }
-}
-
-#[cfg(test)]
-mod filter_some_tests {
- use crate::utils::filter::FilterSome;
-
- #[test]
- fn test_filter_some() {
- let values = [None, Some(23u64), None, Some(12), Some(12), None, Some(23)];
-
- assert_eq!(values.filter_some(), vec![23, 12, 12, 23])
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -
use crate::network::{assert::Assert, error::Error::ArrayIsEmpty, specific::U256};
-use std::ops::{Add, Rem, Shr};
-
-pub(crate) trait Median {
- type Item;
-
- fn median(self) -> Self::Item;
-}
-
-trait Avg {
- fn avg(self, other: Self) -> Self;
-}
-
-trait Averageable:
- Add<Output = Self> + Shr<Output = Self> + From<u8> + Rem<Output = Self> + Copy
-{
-}
-
-impl Averageable for i32 {}
-
-#[cfg(feature = "network_radix")]
-impl Avg for U256 {
- fn avg(self, other: Self) -> Self {
- let one = 1u32;
- let two = U256::from(2u8);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-#[cfg(not(feature = "network_radix"))]
-impl Averageable for U256 {}
-
-impl<T> Avg for T
-where
- T: Averageable,
-{
- fn avg(self, other: Self) -> Self {
- let one = T::from(1);
- let two = T::from(2);
-
- self.shr(one) + other.shr(one) + (self % two + other % two).shr(one)
- }
-}
-
-impl<T> Median for Vec<T>
-where
- T: Copy + Ord + Avg,
-{
- type Item = T;
-
- fn median(self) -> Self::Item {
- let len = self.len();
-
- match len.assert_or_revert(|x| *x > 0, |_| ArrayIsEmpty) {
- 1 => self[0],
- 2 => self[0].avg(self[1]),
- 3 => maybe_pick_median(self[0], self[1], self[2]).unwrap_or_else(|| {
- maybe_pick_median(self[1], self[0], self[2])
- .unwrap_or_else(|| maybe_pick_median(self[1], self[2], self[0]).unwrap())
- }),
- _ => {
- let mut values = self;
- values.sort();
-
- let mid = len / 2;
-
- if len % 2 == 0 {
- values[mid - 1].avg(values[mid])
- } else {
- values[mid]
- }
- }
- }
- }
-}
-
-#[inline]
-fn maybe_pick_median<T>(a: T, b: T, c: T) -> Option<T>
-where
- T: PartialOrd,
-{
- if (b >= a && b <= c) || (b >= c && b <= a) {
- Some(b)
- } else {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{Avg, Median};
- use crate::network::specific::U256;
- use itertools::Itertools;
- use std::fmt::Debug;
-
- #[cfg(feature = "network_radix")]
- use crate::network::radix::u256_ext::U256Ext;
-
- #[allow(clippy::legacy_numeric_constants)]
- #[test]
- fn test_avg() {
- let u256 = U256::max_value(); // 115792089237316195423570985008687907853269984665640564039457584007913129639935
- let u256_max_sub_1 = u256 - U256::from(1u32);
- let u256max_div_2 = u256 / U256::from(2u32);
-
- assert_eq!(u256.avg(U256::from(0u8)), u256max_div_2);
- assert_eq!(u256.avg(U256::from(1u8)), u256max_div_2 + U256::from(1u8));
- assert_eq!(u256.avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!(u256.avg(u256), u256);
-
- assert_eq!((u256_max_sub_1).avg(U256::from(0u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(U256::from(1u8)), u256max_div_2);
- assert_eq!((u256_max_sub_1).avg(u256_max_sub_1), u256_max_sub_1);
- assert_eq!((u256_max_sub_1).avg(u256), u256_max_sub_1);
- }
-
- #[test]
- #[should_panic(expected = "Array is empty")]
- fn test_median_empty_vector() {
- let vec: Vec<i32> = vec![];
-
- vec.median();
- }
-
- #[test]
- fn test_median_single_element() {
- assert_eq!(vec![1].median(), 1);
- }
-
- #[test]
- fn test_median_two_elements() {
- test_all_permutations(vec![1, 3], 2);
- test_all_permutations(vec![1, 2], 1);
- test_all_permutations(vec![1, 1], 1);
- }
-
- #[test]
- fn test_median_three_elements() {
- test_all_permutations(vec![1, 2, 3], 2);
- test_all_permutations(vec![1, 1, 2], 1);
- test_all_permutations(vec![1, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1], 1);
- }
-
- #[test]
- fn test_median_even_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4], 2);
- test_all_permutations(vec![1, 2, 4, 4], 3);
- test_all_permutations(vec![1, 1, 3, 3], 2);
- test_all_permutations(vec![1, 1, 3, 4], 2);
- test_all_permutations(vec![1, 1, 1, 3], 1);
- test_all_permutations(vec![1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 1, 1, 1], 1);
- test_all_permutations(vec![1, 2, 3, 4, 5, 6], 3);
- }
-
- #[test]
- fn test_median_odd_number_of_elements() {
- test_all_permutations(vec![1, 2, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 3, 4, 5], 3);
- test_all_permutations(vec![1, 1, 1, 4, 5], 1);
- test_all_permutations(vec![1, 1, 1, 3, 3], 1);
- test_all_permutations(vec![1, 1, 3, 3, 5], 3);
-
- test_all_permutations(vec![1, 2, 3, 5, 5], 3);
- test_all_permutations(vec![1, 2, 5, 5, 5], 5);
- test_all_permutations(vec![1, 1, 3, 3, 3], 3);
- test_all_permutations(vec![1, 3, 3, 5, 5], 3);
-
- test_all_permutations(vec![1, 2, 2, 2, 2], 2);
- test_all_permutations(vec![1, 1, 1, 1, 2], 1);
- test_all_permutations(vec![1, 1, 1, 1, 1], 1);
-
- test_all_permutations(vec![1, 2, 3, 4, 5, 6, 7], 4);
- }
-
- fn test_all_permutations<T: Copy + Ord + Avg + Debug>(numbers: Vec<T>, expected_value: T) {
- let perms: Vec<Vec<_>> = numbers.iter().permutations(numbers.len()).collect();
-
- for perm in perms {
- let p: Vec<_> = perm.iter().map(|&&v| v).collect();
-
- assert_eq!(p.median(), expected_value);
- }
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -
use crate::network::{
- assert::Unwrap, error::Error, from_bytes_repr::FromBytesRepr, specific::U256,
-};
-
-pub trait Trim<T>
-where
- Self: Sized,
-{
- fn trim_end(&mut self, len: usize) -> T;
-}
-
-impl Trim<Vec<u8>> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> Self {
- if len >= self.len() {
- std::mem::take(self)
- } else {
- self.split_off(self.len() - len)
- }
- }
-}
-
-impl Trim<U256> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> U256 {
- U256::from_bytes_repr(self.trim_end(len))
- }
-}
-
-impl Trim<usize> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> usize {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-impl Trim<u64> for Vec<u8> {
- fn trim_end(&mut self, len: usize) -> u64 {
- let y: U256 = self.trim_end(len);
- y.try_into().unwrap_or_revert(|_| Error::NumberOverflow(y))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{
- network::specific::U256,
- protocol::constants::{REDSTONE_MARKER, REDSTONE_MARKER_BS},
- utils::trim::Trim,
- };
-
- const MARKER_DECIMAL: u64 = 823907890102272;
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.into()
- }
-
- #[test]
- fn test_trim_end_number() {
- let (rest, result): (_, U256) = test_trim_end(3);
- assert_eq!(result, (256u32.pow(2) * 30).into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER[..6]);
-
- let (_, result): (_, u64) = test_trim_end(3);
- assert_eq!(result, 256u64.pow(2) * 30);
-
- let (_, result): (_, usize) = test_trim_end(3);
- assert_eq!(result, 256usize.pow(2) * 30);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(3);
- assert_eq!(result.as_slice(), &REDSTONE_MARKER[6..]);
- }
-
- #[test]
- fn test_trim_end_number_null() {
- let (rest, result): (_, U256) = test_trim_end(0);
- assert_eq!(result, 0u32.into());
- assert_eq!(rest.as_slice(), &REDSTONE_MARKER);
-
- let (_, result): (_, u64) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, usize) = test_trim_end(0);
- assert_eq!(result, 0);
-
- let (_, result): (_, Vec<u8>) = test_trim_end(0);
- assert_eq!(result, Vec::<u8>::new());
- }
-
- #[test]
- fn test_trim_end_whole() {
- test_trim_end_whole_size(REDSTONE_MARKER_BS);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 1);
- test_trim_end_whole_size(REDSTONE_MARKER_BS - 2);
- test_trim_end_whole_size(REDSTONE_MARKER_BS + 1);
- }
-
- fn test_trim_end_whole_size(size: usize) {
- let (rest, result): (_, U256) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL.into());
- assert_eq!(
- rest.as_slice().len(),
- REDSTONE_MARKER_BS - size.min(REDSTONE_MARKER_BS)
- );
-
- let (_, result): (_, u64) = test_trim_end(size);
- assert_eq!(result, MARKER_DECIMAL);
-
- let (_, result): (_, usize) = test_trim_end(size);
- assert_eq!(result, 823907890102272usize);
-
- let (_rest, result): (_, Vec<u8>) = test_trim_end(size);
- assert_eq!(result.as_slice().len(), size.min(REDSTONE_MARKER_BS));
- }
-
- #[test]
- fn test_trim_end_u64() {
- let mut bytes = vec![255, 255, 255, 255, 255, 255, 255, 255, 255];
- let x: u64 = bytes.trim_end(8);
-
- let expected_bytes = vec![255];
-
- assert_eq!(bytes, expected_bytes);
- assert_eq!(x, 18446744073709551615);
- }
-
- #[should_panic(expected = "Number overflow: 18591708106338011145")]
- #[test]
- fn test_trim_end_u64_overflow() {
- let mut bytes = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9];
-
- let _: u64 = bytes.trim_end(9);
- }
-
- #[allow(dead_code)]
- trait TestTrimEnd<T>
- where
- Self: Sized,
- {
- fn test_trim_end(size: usize) -> (Self, T);
- }
-
- fn test_trim_end<T>(size: usize) -> (Vec<u8>, T)
- where
- Vec<u8>: Trim<T>,
- {
- let mut bytes = redstone_marker_bytes();
- let rest = bytes.trim_end(size);
- (bytes, rest)
- }
-}
-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -
pub trait TrimZeros {
- fn trim_zeros(self) -> Self;
-}
-
-impl TrimZeros for Vec<u8> {
- fn trim_zeros(self) -> Self {
- let mut res = self.len();
-
- for i in (0..self.len()).rev() {
- if self[i] != 0 {
- break;
- }
-
- res = i;
- }
-
- let (rest, _) = self.split_at(res);
-
- rest.into()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::{protocol::constants::REDSTONE_MARKER, utils::trim_zeros::TrimZeros};
-
- fn redstone_marker_bytes() -> Vec<u8> {
- REDSTONE_MARKER.as_slice().into()
- }
-
- #[test]
- fn test_trim_zeros() {
- let trimmed = redstone_marker_bytes().trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
-
- let trimmed = trimmed.trim_zeros();
- assert_eq!(trimmed.as_slice(), &REDSTONE_MARKER[..7]);
- }
-
- #[test]
- fn test_trim_zeros_empty() {
- let trimmed = Vec::<u8>::default().trim_zeros();
- assert_eq!(trimmed, Vec::<u8>::default());
- }
-}
-
fn:
) to \
- restrict the search to a given item kind.","Accepted kinds are: fn
, mod
, struct
, \
- enum
, trait
, type
, macro
, \
- and const
.","Search functions by type signature (e.g., vec -> usize
or \
- -> vec
or String, enum:Cow -> bool
)","You can look for items with an exact name by putting double quotes around \
- your request: \"string\"
","Look for functions that accept or return \
- slices and \
- arrays by writing \
- square brackets (e.g., -> [u8]
or [] -> Option
)","Look for items inside another one by searching for a path: vec::Vec
",].map(x=>""+x+"
").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="${value.replaceAll(" ", " ")}
`}else{error[index]=value}});output+=`Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,\nas it avoids reallocation if possible. Additionally, if the element type\nT
overrides clone_from()
, this will reuse the resources of self
’s\nelements as well.
let x = vec![5, 6, 7];\nlet mut y = vec![8, 9, 10];\nlet yp: *const i32 = y.as_ptr();\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no reallocation occurred\nassert_eq!(yp, y.as_ptr());
Extend implementation that copies elements out of references before pushing them onto the Vec.
\nThis implementation is specialized for slice iterators, where it uses copy_from_slice
to\nappend the entire slice at once.
extend_one
)extend_one
)extend_one
)extend_one
)Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has\nconstant time complexity.
\n