code
stringlengths 11
306k
| docstring
stringlengths 1
39.1k
| func_name
stringlengths 0
97
| language
stringclasses 1
value | repo
stringclasses 959
values | path
stringlengths 8
160
| url
stringlengths 49
212
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
pub fn new(v: [u8; 32]) -> Self {
v.pack()
} | Creates a new `Bytes32`. | new | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn from_tx_hash(h: &packed::Byte32) -> Self {
let mut inner = [0u8; 10];
inner.copy_from_slice(&h.as_slice()[..10]);
inner.pack()
} | Creates a new `ProposalShortId` from a transaction hash. | from_tx_hash | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn zero() -> Self {
Self::default()
} | Creates a new `ProposalShortId` whose bits are all zeros. | zero | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn new(v: [u8; 10]) -> Self {
v.pack()
} | Creates a new `ProposalShortId`. | new | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn new(tx_hash: packed::Byte32, index: u32) -> Self {
packed::OutPoint::new_builder()
.tx_hash(tx_hash)
.index(index.pack())
.build()
} | Creates a new `OutPoint`. | new | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn null() -> Self {
packed::OutPoint::new_builder()
.index(u32::MAX.pack())
.build()
} | Creates a new null `OutPoint`. | null | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn is_null(&self) -> bool {
self.tx_hash().is_zero() && Unpack::<u32>::unpack(&self.index()) == u32::MAX
} | Checks whether self is a null `OutPoint`. | is_null | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn to_cell_key(&self) -> Vec<u8> {
let mut key = Vec::with_capacity(36);
let index: u32 = self.index().unpack();
key.extend_from_slice(self.tx_hash().as_slice());
key.extend_from_slice(&index.to_be_bytes());
key
} | Generates a binary data to be used as a key for indexing cells in storage.
# Notice
The difference between [`Self::as_slice()`](../prelude/trait.Entity.html#tymethod.as_slice)
and [`Self::to_cell_key()`](#method.to_cell_key) is the byteorder of the field `index`.
- Uses little endian for the field `index` in serialization.
Because in the real world, the little endian machines make up the majority, we can cast
it as a number without re-order the bytes.
- Uses big endian for the field `index` to index cells in storage.
So we can use `tx_hash` as key prefix to seek the cells from storage in the forward
order, so as to traverse cells in the forward order too. | to_cell_key | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn new(previous_output: packed::OutPoint, block_number: BlockNumber) -> Self {
packed::CellInput::new_builder()
.since(block_number.pack())
.previous_output(previous_output)
.build()
} | Creates a new `CellInput`. | new | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn new_cellbase_input(block_number: BlockNumber) -> Self {
Self::new(packed::OutPoint::null(), block_number)
} | Creates a new `CellInput` with a null `OutPoint`. | new_cellbase_input | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn into_witness(self) -> packed::Bytes {
packed::CellbaseWitness::new_builder()
.lock(self)
.build()
.as_bytes()
.pack()
} | Converts self into bytes of [`CellbaseWitness`](struct.CellbaseWitness.html). | into_witness | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn from_witness(witness: packed::Bytes) -> Option<Self> {
packed::CellbaseWitness::from_slice(&witness.raw_data())
.map(|cellbase_witness| cellbase_witness.lock())
.ok()
} | Converts from bytes of [`CellbaseWitness`](struct.CellbaseWitness.html). | from_witness | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn is_hash_type_type(&self) -> bool {
Into::<u8>::into(self.hash_type()) == Into::<u8>::into(core::ScriptHashType::Type)
} | Checks whether the own [`hash_type`](#method.hash_type) is
[`Type`](../core/enum.ScriptHashType.html#variant.Type). | is_hash_type_type | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn is_cellbase(&self) -> bool {
let raw_tx = self.raw();
raw_tx.inputs().len() == 1
&& self.witnesses().len() == 1
&& raw_tx
.inputs()
.get(0)
.should_be_ok()
.previous_output()
.is_null()
} | Checks whether self is a cellbase. | is_cellbase | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn proposal_short_id(&self) -> packed::ProposalShortId {
packed::ProposalShortId::from_tx_hash(&self.calc_tx_hash())
} | Generates a proposal short id after calculating the transaction hash. | proposal_short_id | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn as_uncle(&self) -> packed::UncleBlock {
packed::UncleBlock::new_builder()
.header(self.header())
.proposals(self.proposals())
.build()
} | Converts self to an uncle block. | as_uncle | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extra_field(&self, index: usize) -> Option<bytes::Bytes> {
let count = self.count_extra_fields();
if count > index {
let slice = self.as_slice();
let i = (1 + Self::FIELD_COUNT + index) * molecule::NUMBER_SIZE;
let start = molecule::unpack_number(&slice[i..]) as usize;
if count == index + 1 {
Some(self.as_bytes().slice(start..))
} else {
let j = i + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[j..]) as usize;
Some(self.as_bytes().slice(start..end))
}
} else {
None
}
} | Gets the i-th extra field if it exists; i started from 0. | extra_field | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extension(&self) -> Option<packed::Bytes> {
self.extra_field(0)
.map(|data| packed::Bytes::from_slice(&data).unwrap())
} | Gets the extension field if it existed.
# Panics
Panics if the first extra field exists but not a valid [`Bytes`](struct.Bytes.html). | extension | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn txs_len(&self) -> usize {
self.prefilled_transactions().len() + self.short_ids().len()
} | Calculates the length of transactions. | txs_len | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extra_field(&self, index: usize) -> Option<bytes::Bytes> {
let count = self.count_extra_fields();
if count > index {
let slice = self.as_slice();
let i = (1 + Self::FIELD_COUNT + index) * molecule::NUMBER_SIZE;
let start = molecule::unpack_number(&slice[i..]) as usize;
if count == index + 1 {
Some(self.as_bytes().slice(start..))
} else {
let j = i + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[j..]) as usize;
Some(self.as_bytes().slice(start..end))
}
} else {
None
}
} | Gets the i-th extra field if it exists; i started from 0. | extra_field | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extension(&self) -> Option<packed::Bytes> {
self.extra_field(0)
.map(|data| packed::Bytes::from_slice(&data).unwrap())
} | Gets the extension field if it existed.
# Panics
Panics if the first extra field exists but not a valid [`Bytes`](struct.Bytes.html). | extension | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn as_v0(&self) -> packed::Block {
packed::Block::new_unchecked(self.as_bytes())
} | Converts to a compatible [`Block`](struct.Block.html) with an extra field. | as_v0 | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extra_field(&self, index: usize) -> Option<&[u8]> {
let count = self.count_extra_fields();
if count > index {
let slice = self.as_slice();
let i = (1 + Self::FIELD_COUNT + index) * molecule::NUMBER_SIZE;
let start = molecule::unpack_number(&slice[i..]) as usize;
if count == index + 1 {
Some(&self.as_slice()[start..])
} else {
let j = i + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[j..]) as usize;
Some(&self.as_slice()[start..end])
}
} else {
None
}
} | Gets the i-th extra field if it exists; i started from 0. | extra_field | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn extension(&self) -> Option<packed::BytesReader> {
self.extra_field(0)
.map(|data| packed::BytesReader::from_slice(data).unwrap())
} | Gets the extension field if it existed.
# Panics
Panics if the first extra field exists but not a valid [`BytesReader`](struct.BytesReader.html). | extension | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn as_v0(&self) -> packed::BlockReader {
packed::BlockReader::new_unchecked(self.as_slice())
} | Converts to a compatible [`BlockReader`](struct.BlockReader.html) with an extra field. | as_v0 | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn as_v0(&self) -> packed::CompactBlock {
packed::CompactBlock::new_unchecked(self.as_bytes())
} | Converts to a compatible [`CompactBlock`](struct.CompactBlock.html) with an extra field. | as_v0 | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn as_v0(&self) -> packed::CompactBlockReader {
packed::CompactBlockReader::new_unchecked(self.as_slice())
} | Converts to a compatible [`CompactBlockReader`](struct.CompactBlockReader.html) with an extra field. | as_v0 | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn is_default(&self) -> bool {
let default = Self::default();
self.as_slice() == default.as_slice()
} | Checks if the `HeaderDigest` is the default value. | is_default | rust | nervosnetwork/ckb | util/gen-types/src/extension/shortcut.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/shortcut.rs | MIT |
pub fn occupied_capacity(&self) -> CapacityResult<Capacity> {
Capacity::bytes(self.args().raw_data().len() + 32 + 1)
} | Calculates the occupied capacity of [`Script`].
Includes [`code_hash`] (32), [`hash_type`] (1) and [`args`] (calculated).
[`Script`]: https://github.com/nervosnetwork/ckb/blob/v0.36.0/util/types/schemas/blockchain.mol#L30-L34
[`code_hash`]: #method.code_hash
[`hash_type`]: #method.hash_type
[`args`]: #method.args | occupied_capacity | rust | nervosnetwork/ckb | util/gen-types/src/extension/capacity.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/capacity.rs | MIT |
pub fn occupied_capacity(&self, data_capacity: Capacity) -> CapacityResult<Capacity> {
Capacity::bytes(8)
.and_then(|x| x.safe_add(data_capacity))
.and_then(|x| self.lock().occupied_capacity().and_then(|y| y.safe_add(x)))
.and_then(|x| {
self.type_()
.to_opt()
.as_ref()
.map(packed::Script::occupied_capacity)
.transpose()
.and_then(|y| y.unwrap_or_else(Capacity::zero).safe_add(x))
})
} | Calculates the occupied capacity of [`CellOutput`].
Includes [`output_data`] (provided), [`capacity`] (8), [`lock`] (calculated) and [`type`] (calculated).
[`CellOutput`]: https://github.com/nervosnetwork/ckb/blob/v0.36.0/util/types/schemas/blockchain.mol#L46-L50
[`output_data`]: https://github.com/nervosnetwork/ckb/blob/v0.36.0/util/types/schemas/blockchain.mol#L63
[`capacity`]: #method.capacity
[`lock`]: #method.lock
[`type`]: #method.type_ | occupied_capacity | rust | nervosnetwork/ckb | util/gen-types/src/extension/capacity.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/capacity.rs | MIT |
pub fn is_lack_of_capacity(&self, data_capacity: Capacity) -> CapacityResult<bool> {
self.occupied_capacity(data_capacity)
.map(|cap| cap > self.capacity().unpack())
} | Returns if the [`capacity`] in `CellOutput` is smaller than the [`occupied capacity`].
[`capacity`]: #method.capacity
[`occupied capacity`]: #method.occupied_capacity | is_lack_of_capacity | rust | nervosnetwork/ckb | util/gen-types/src/extension/capacity.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/capacity.rs | MIT |
pub fn build_exact_capacity(
self,
data_capacity: Capacity,
) -> CapacityResult<packed::CellOutput> {
Capacity::bytes(8)
.and_then(|x| x.safe_add(data_capacity))
.and_then(|x| self.lock.occupied_capacity().and_then(|y| y.safe_add(x)))
.and_then(|x| {
self.type_
.to_opt()
.as_ref()
.map(packed::Script::occupied_capacity)
.transpose()
.and_then(|y| y.unwrap_or_else(Capacity::zero).safe_add(x))
})
.map(|x| self.capacity(x.pack()).build())
} | Build a [`CellOutput`] and sets its [`capacity`] equal to its [`occupied capacity`] exactly.
[`CellOutput`]: struct.CellOutput.html
[`capacity`]: #method.capacity
[`occupied capacity`]: struct.CellOutput.html#method.occupied_capacity | build_exact_capacity | rust | nervosnetwork/ckb | util/gen-types/src/extension/capacity.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/capacity.rs | MIT |
pub fn total_capacity(&self) -> CapacityResult<Capacity> {
self.as_reader()
.iter()
.map(|output| {
let cap: Capacity = output.capacity().unpack();
cap
})
.try_fold(Capacity::zero(), Capacity::safe_add)
} | Sums the capacities of all [`CellOutput`]s in the vector.
[`CellOutput`]: struct.CellOutput.html#method.occupied_capacity | total_capacity | rust | nervosnetwork/ckb | util/gen-types/src/extension/capacity.rs | https://github.com/nervosnetwork/ckb/blob/master/util/gen-types/src/extension/capacity.rs | MIT |
fn reduce(&mut self) {
let g = self.numer.gcd(&self.denom);
self.numer = &self.numer / &g;
self.denom = &self.denom / &g;
} | Puts self into lowest terms, with denom > 0. | reduce | rust | nervosnetwork/ckb | util/rational/src/lib.rs | https://github.com/nervosnetwork/ckb/blob/master/util/rational/src/lib.rs | MIT |
pub const fn new(numer: u64, denom: u64) -> Self {
Self { numer, denom }
} | Creates a ratio numer / denom. | new | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn numer(&self) -> u64 {
self.numer
} | The numerator in ratio numerator / denominator. | numer | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn denom(&self) -> u64 {
self.denom
} | The denominator in ratio numerator / denominator. | denom | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
fn into_capacity(self) -> Capacity;
}
impl IntoCapacity for Capacity {
fn into_capacity(self) -> Capacity {
self
}
} | Converts `self` into `Capacity`. | into_capacity | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub const fn zero() -> Self {
Capacity(0)
} | Capacity of zero Shannons. | zero | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub const fn one() -> Self {
Capacity(1)
} | Capacity of one Shannon. | one | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub const fn shannons(val: u64) -> Self {
Capacity(val)
} | Views the capacity as Shannons. | shannons | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn bytes(val: usize) -> Result<Self> {
(val as u64)
.checked_mul(BYTE_SHANNONS)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
} | Views the capacity as CKBytes. | bytes | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn as_u64(self) -> u64 {
self.0
} | Views the capacity as Shannons. | as_u64 | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn safe_add<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_add(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
} | Adds self and rhs and checks overflow error. | safe_add | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn safe_sub<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_sub(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
} | Subtracts self and rhs and checks overflow error. | safe_sub | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn safe_mul<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_mul(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
} | Multiplies self and rhs and checks overflow error. | safe_mul | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn safe_mul_ratio(self, ratio: Ratio) -> Result<Self> {
self.0
.checked_mul(ratio.numer())
.and_then(|ret| ret.checked_div(ratio.denom()))
.map(Capacity::shannons)
.ok_or(Error::Overflow)
} | Multiplies self with a ratio and checks overflow error. | safe_mul_ratio | rust | nervosnetwork/ckb | util/occupied-capacity/core/src/units.rs | https://github.com/nervosnetwork/ckb/blob/master/util/occupied-capacity/core/src/units.rs | MIT |
pub fn init(config: Config, handle: Handle) -> Result<Guard, String> {
if config.exporter.is_empty() {
let _ignored = ckb_metrics::METRICS_SERVICE_ENABLED.set(false);
return Ok(Guard::Off);
}
for (name, exporter) in config.exporter {
check_exporter_name(&name)?;
run_exporter(exporter, &handle)?;
}
// The .set() method's return value can indicate whether the value has set or not.
// Just ignore its return value
// I don't care this because CKB only initializes the ckb-metrics-service once.
let _ignored = ckb_metrics::METRICS_SERVICE_ENABLED.set(true);
Ok(Guard::On)
} | Initializes the metrics service and lets it run in the background.
Returns [Guard](enum.Guard.html) if succeeded, or an `String` to describes the reason for the failure. | init | rust | nervosnetwork/ckb | util/metrics-service/src/lib.rs | https://github.com/nervosnetwork/ckb/blob/master/util/metrics-service/src/lib.rs | MIT |
pub fn new(config: NetworkAlertConfig) -> Self {
let pubkeys = config
.public_keys
.iter()
.map(|raw| Pubkey::from_slice(raw.as_bytes()))
.collect::<Result<HashSet<Pubkey>, _>>()
.expect("builtin pubkeys");
Verifier { config, pubkeys }
} | Init with ckb alert config | new | rust | nervosnetwork/ckb | util/network-alert/src/verifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/verifier.rs | MIT |
pub fn verify_signatures(&self, alert: &packed::Alert) -> Result<(), AnyError> {
trace!("Verifying alert {:?}", alert);
let message = Message::from_slice(alert.calc_alert_hash().as_slice())?;
let signatures: Vec<Signature> = alert
.signatures()
.into_iter()
.filter_map(
|sig_data| match Signature::from_slice(sig_data.as_reader().raw_data()) {
Ok(sig) => {
if sig.is_valid() {
Some(sig)
} else {
debug!("invalid signature: {:?}", sig);
None
}
}
Err(err) => {
debug!("signature error: {}", err);
None
}
},
)
.collect();
verify_m_of_n(
&message,
self.config.signatures_threshold,
&signatures,
&self.pubkeys,
)
.map_err(|err| err.kind())?;
Ok(())
} | Verify signatures | verify_signatures | rust | nervosnetwork/ckb | util/network-alert/src/verifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/verifier.rs | MIT |
pub fn new(
client_version: String,
notify_controller: NotifyController,
signature_config: NetworkAlertConfig,
) -> Self {
AlertRelayer {
notifier: Arc::new(Mutex::new(Notifier::new(client_version, notify_controller))),
verifier: Arc::new(Verifier::new(signature_config)),
known_lists: LruCache::new(KNOWN_LIST_SIZE),
}
} | Init | new | rust | nervosnetwork/ckb | util/network-alert/src/alert_relayer.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/alert_relayer.rs | MIT |
pub fn notifier(&self) -> &Arc<Mutex<Notifier>> {
&self.notifier
} | Get notifier | notifier | rust | nervosnetwork/ckb | util/network-alert/src/alert_relayer.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/alert_relayer.rs | MIT |
pub fn verifier(&self) -> &Arc<Verifier> {
&self.verifier
} | Get verifier | verifier | rust | nervosnetwork/ckb | util/network-alert/src/alert_relayer.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/alert_relayer.rs | MIT |
pub fn new(client_version: String, notify_controller: NotifyController) -> Self {
let parsed_client_version = match Version::parse(&client_version) {
Ok(version) => Some(version),
Err(err) => {
error!(
"Invalid version {} for alert notifier: {}",
client_version, err
);
None
}
};
Notifier {
cancel_filter: LruCache::new(CANCEL_FILTER_SIZE),
received_alerts: Default::default(),
noticed_alerts: Vec::new(),
client_version: parsed_client_version,
notify_controller,
}
} | Init | new | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn add(&mut self, alert: &Alert) {
let alert_id = alert.raw().id().unpack();
let alert_cancel = alert.raw().cancel().unpack();
if self.has_received(alert_id) {
return;
}
// checkout cancel_id
if alert_cancel > 0 {
self.cancel(alert_cancel);
}
// add to received alerts
self.received_alerts.insert(alert_id, alert.clone());
// check conditions, figure out do we need to notice this alert
if !self.is_version_effective(alert) {
debug!("Received a version ineffective alert {:?}", alert);
return;
}
if self.noticed_alerts.contains(alert) {
return;
}
self.notify_controller.notify_network_alert(alert.clone());
self.noticed_alerts.push(alert.clone());
// sort by priority
self.noticed_alerts.sort_by_key(|a| {
let priority: u32 = a.raw().priority().unpack();
u32::MAX - priority
});
} | Add an alert | add | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn cancel(&mut self, cancel_id: u32) {
self.cancel_filter.put(cancel_id, ());
self.received_alerts.remove(&cancel_id);
self.noticed_alerts.retain(|a| {
let id: u32 = a.raw().id().unpack();
id != cancel_id
});
} | Cancel alert id | cancel | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn clear_expired_alerts(&mut self, now: u64) {
self.received_alerts.retain(|_id, alert| {
let notice_until: u64 = alert.raw().notice_until().unpack();
notice_until > now
});
self.noticed_alerts.retain(|a| {
let notice_until: u64 = a.raw().notice_until().unpack();
notice_until > now
});
} | Clear all expired alerts | clear_expired_alerts | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn has_received(&self, id: u32) -> bool {
self.received_alerts.contains_key(&id) || self.cancel_filter.contains(&id)
} | Whether id received | has_received | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn received_alerts(&self) -> Vec<Alert> {
self.received_alerts.values().cloned().collect()
} | All unexpired alerts | received_alerts | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn noticed_alerts(&self) -> Vec<Alert> {
self.noticed_alerts.clone()
} | Alerts that self node should noticed | noticed_alerts | rust | nervosnetwork/ckb | util/network-alert/src/notifier.rs | https://github.com/nervosnetwork/ckb/blob/master/util/network-alert/src/notifier.rs | MIT |
pub fn new(shared: Shared, target: PathBuf) -> Self {
Export { shared, target }
} | Creates the export job. | new | rust | nervosnetwork/ckb | util/instrument/src/export.rs | https://github.com/nervosnetwork/ckb/blob/master/util/instrument/src/export.rs | MIT |
fn file_name(&self) -> String {
format!("{}.{}", self.shared.consensus().id, "json")
} | export file name | file_name | rust | nervosnetwork/ckb | util/instrument/src/export.rs | https://github.com/nervosnetwork/ckb/blob/master/util/instrument/src/export.rs | MIT |
pub fn execute(self) -> Result<(), Box<dyn Error>> {
fs::create_dir_all(&self.target)?;
self.write_to_json()
} | Executes the export job. | execute | rust | nervosnetwork/ckb | util/instrument/src/export.rs | https://github.com/nervosnetwork/ckb/blob/master/util/instrument/src/export.rs | MIT |
pub fn new(chain: ChainController, source: PathBuf) -> Self {
Import { chain, source }
} | Creates a new import job. | new | rust | nervosnetwork/ckb | util/instrument/src/import.rs | https://github.com/nervosnetwork/ckb/blob/master/util/instrument/src/import.rs | MIT |
pub fn execute(self) -> Result<(), Box<dyn Error>> {
self.read_from_json()
} | Executes the import job. | execute | rust | nervosnetwork/ckb | util/instrument/src/import.rs | https://github.com/nervosnetwork/ckb/blob/master/util/instrument/src/import.rs | MIT |
pub fn verify_m_of_n<S>(
message: &Message,
m_threshold: usize,
sigs: &[Signature],
pks: &HashSet<Pubkey, S>,
) -> Result<(), Error>
where
S: BuildHasher,
{
if sigs.len() > pks.len() {
return Err(ErrorKind::SigCountOverflow.into());
}
if m_threshold > sigs.len() {
return Err(ErrorKind::SigNotEnough.into());
}
let mut used_pks: HashSet<Pubkey> = HashSet::with_capacity(m_threshold);
let verified_sig_count = sigs
.iter()
.filter_map(|sig| {
trace!(
"Recover sig {:x?} with message {:x?}",
&sig.serialize()[..],
message.as_ref()
);
match sig.recover(message) {
Ok(pubkey) => Some(pubkey),
Err(err) => {
debug!("recover secp256k1 sig error: {}", err);
None
}
}
})
.filter(|rec_pk| pks.contains(rec_pk) && used_pks.insert(rec_pk.to_owned()))
.take(m_threshold)
.count();
if verified_sig_count < m_threshold {
return Err(ErrorKind::Threshold {
pass_sigs: verified_sig_count,
threshold: m_threshold,
}
.into());
}
Ok(())
} | Verifies m of n signatures.
Example 2 of 3 sigs: [s1, s3], pks: [pk1, pk2, pk3] | verify_m_of_n | rust | nervosnetwork/ckb | util/multisig/src/secp256k1.rs | https://github.com/nervosnetwork/ckb/blob/master/util/multisig/src/secp256k1.rs | MIT |
pub fn from_trimmed_str(input: &str) -> Result<Self, FromStrError> {
let bytes = input.as_bytes();
let len = bytes.len();
if len > $bytes_size * 2 {
Err(FromStrError::InvalidLength(len))
} else if len == 0 {
Ok(Self::default())
} else if bytes[0] == b'0' {
if len == 1 {
Ok(Self::default())
} else {
Err(FromStrError::InvalidCharacter { chr: b'0', idx: 0 })
}
} else {
let mut ret = Self::default();
let mut idx = 0;
let mut unit_idx = ($bytes_size * 2 - len) / 2;
let mut high = len % 2 == 0;
for chr in input.bytes() {
let val = if high {
DICT_HEX_HI[usize::from(chr)]
} else {
DICT_HEX_LO[usize::from(chr)]
};
if val == DICT_HEX_ERROR {
return Err(FromStrError::InvalidCharacter { chr, idx });
}
idx += 1;
ret.0[unit_idx] |= val;
if high {
high = false;
} else {
high = true;
unit_idx += 1;
}
}
Ok(ret)
}
} |
let mut inner = [0u8; BYTES_SIZE];
{
let actual = Hash(inner.clone());
let expected1 = Hash::from_trimmed_str("").unwrap();
let expected2 = Hash::from_trimmed_str("0").unwrap();
assert_eq!(actual, expected1);
assert_eq!(actual, expected2);
}
{
inner[BYTES_SIZE - 1] = 1;
let actual = Hash(inner);
let expected = Hash::from_trimmed_str("1").unwrap();
assert_eq!(actual, expected);
}
{
assert!(Hash::from_trimmed_str("00").is_err());
assert!(Hash::from_trimmed_str("000").is_err());
assert!(Hash::from_trimmed_str("0000").is_err());
assert!(Hash::from_trimmed_str("01").is_err());
assert!(Hash::from_trimmed_str("001").is_err());
assert!(Hash::from_trimmed_str("0001").is_err());
}
``` | from_trimmed_str | rust | nervosnetwork/ckb | util/fixed-hash/core/src/std_str.rs | https://github.com/nervosnetwork/ckb/blob/master/util/fixed-hash/core/src/std_str.rs | MIT |
pub fn load_for_subcommand<P: AsRef<Path>>(
root_dir: P,
subcommand_name: &str,
) -> Result<AppConfig, ExitCode> {
match subcommand_name {
cli::CMD_MINER => {
let resource = ensure_ckb_dir(Resource::miner_config(root_dir.as_ref()))?;
let config = MinerAppConfig::load_from_slice(&resource.get()?)?;
Ok(AppConfig::with_miner(
config.derive_options(root_dir.as_ref())?,
))
}
_ => {
let resource = ensure_ckb_dir(Resource::ckb_config(root_dir.as_ref()))?;
let config = CKBAppConfig::load_from_slice(&resource.get()?)?;
Ok(AppConfig::with_ckb(
config.derive_options(root_dir.as_ref(), subcommand_name)?,
))
}
}
} | Reads the config file for the subcommand.
This will reads the `ckb-miner.toml` in the CKB directory for `ckb miner`, and `ckb.toml`
for all other subcommands. | load_for_subcommand | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn logger(&self) -> &LogConfig {
match self {
AppConfig::CKB(config) => &config.logger,
AppConfig::Miner(config) => &config.logger,
}
} | Gets logger options. | logger | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn metrics(&self) -> &MetricsConfig {
match self {
AppConfig::CKB(config) => &config.metrics,
AppConfig::Miner(config) => &config.metrics,
}
} | Gets metrics options. | metrics | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn memory_tracker(&self) -> &MemoryTrackerConfig {
match self {
AppConfig::CKB(config) => &config.memory_tracker,
AppConfig::Miner(config) => &config.memory_tracker,
}
} | Gets memory tracker options. | memory_tracker | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn chain_spec(&self) -> Result<ChainSpec, ExitCode> {
let spec_resource = match self {
AppConfig::CKB(config) => &config.chain.spec,
AppConfig::Miner(config) => &config.chain.spec,
};
ChainSpec::load_from(spec_resource).map_err(|err| {
eprintln!("{err}");
ExitCode::Config
})
} | Gets chain spec. | chain_spec | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn into_ckb(self) -> Result<Box<CKBAppConfig>, ExitCode> {
match self {
AppConfig::CKB(config) => Ok(config),
_ => {
eprintln!("Unmatched config file");
Err(ExitCode::Failure)
}
}
} | Unpacks the parsed ckb.toml config file.
Panics when this is a parsed ckb-miner.toml. | into_ckb | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn into_miner(self) -> Result<Box<MinerAppConfig>, ExitCode> {
match self {
AppConfig::Miner(config) => Ok(config),
_ => {
eprintln!("Unmatched config file");
Err(ExitCode::Failure)
}
}
} | Unpacks the parsed ckb-miner.toml config file.
Panics when this is a parsed ckb.toml. | into_miner | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn set_bin_name(&mut self, bin_name: String) {
match self {
AppConfig::CKB(config) => config.bin_name = bin_name,
AppConfig::Miner(config) => config.bin_name = bin_name,
}
} | Set the binary name with full path. | set_bin_name | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn load_from_slice(slice: &[u8]) -> Result<Self, ExitCode> {
let legacy_config: legacy::CKBAppConfig = toml::from_slice(slice)?;
for field in legacy_config.deprecated_fields() {
eprintln!(
"WARN: the option \"{}\" in configuration files is deprecated since v{}.",
field.path, field.since
);
}
Ok(legacy_config.into())
} | Load a new instance from a file | load_from_slice | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn load_from_slice(slice: &[u8]) -> Result<Self, ExitCode> {
let legacy_config: legacy::MinerAppConfig = toml::from_slice(slice)?;
for field in legacy_config.deprecated_fields() {
eprintln!(
"WARN: the option \"{}\" in configuration files is deprecated since v{}.",
field.path, field.since
);
}
Ok(legacy_config.into())
} | Load a new instance from a file. | load_from_slice | rust | nervosnetwork/ckb | util/app-config/src/app_config.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/app_config.rs | MIT |
pub fn into(self) -> i32 {
self as i32
} | Converts into signed 32-bit integer which can be used as the process exit status. | into | rust | nervosnetwork/ckb | util/app-config/src/exit_code.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/exit_code.rs | MIT |
pub fn is_unset(&self) -> bool {
self.genesis_message.is_none()
} | No specified parameters for chain spec. | is_unset | rust | nervosnetwork/ckb | util/app-config/src/args.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/args.rs | MIT |
pub fn key_value_pairs(&self) -> Vec<(&'static str, String)> {
let mut vec = Vec::new();
let genesis_message = self
.genesis_message
.clone()
.unwrap_or_else(|| unix_time_as_millis().to_string());
vec.push(("genesis_message", genesis_message));
vec
} | Generates a vector of key-value pairs. | key_value_pairs | rust | nervosnetwork/ckb | util/app-config/src/args.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/args.rs | MIT |
pub fn adjust<P: AsRef<Path>>(&mut self, root_dir: &Path, data_dir: P, name: &str) {
// If path is not set, use the default path
if self.path.to_str().is_none() || self.path.to_str() == Some("") {
self.path = data_dir.as_ref().to_path_buf().join(name);
} else if self.path.is_relative() {
// If the path is relative, set the base path to `ckb.toml`
self.path = root_dir.to_path_buf().join(&self.path)
}
// If options file is a relative path, set the base path to `ckb.toml`
if let Some(file) = self.options_file.iter_mut().next() {
if file.is_relative() {
let file_new = root_dir.to_path_buf().join(&file);
*file = file_new;
}
}
} | Canonicalizes paths in the config options.
If `self.path` is not set, set it to `data_dir / name`.
If `self.path` or `self.options_file` is relative, convert them to absolute path using
`root_dir` as current working directory. | adjust | rust | nervosnetwork/ckb | util/app-config/src/configs/db.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/db.rs | MIT |
pub fn net_enable(&self) -> bool {
self.modules.contains(&Module::Net)
} | Checks whether the Net module is enabled. | net_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn chain_enable(&self) -> bool {
self.modules.contains(&Module::Chain)
} | Checks whether the Chain module is enabled. | chain_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn miner_enable(&self) -> bool {
self.modules.contains(&Module::Miner)
} | Checks whether the Miner module is enabled. | miner_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn pool_enable(&self) -> bool {
self.modules.contains(&Module::Pool)
} | Checks whether the Pool module is enabled. | pool_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn experiment_enable(&self) -> bool {
self.modules.contains(&Module::Experiment)
} | Checks whether the Experiment module is enabled. | experiment_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn stats_enable(&self) -> bool {
self.modules.contains(&Module::Stats)
} | Checks whether the Stats module is enabled. | stats_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn subscription_enable(&self) -> bool {
self.modules.contains(&Module::Subscription)
} | Checks whether the Subscription module is enabled. | subscription_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn integration_test_enable(&self) -> bool {
self.modules.contains(&Module::IntegrationTest)
} | Checks whether the IntegrationTest module is enabled. | integration_test_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn alert_enable(&self) -> bool {
self.modules.contains(&Module::Alert)
} | Checks whether the Alert module is enabled. | alert_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn debug_enable(&self) -> bool {
self.modules.contains(&Module::Debug)
} | Checks whether the Debug module is enabled. | debug_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn indexer_enable(&self) -> bool {
self.modules.contains(&Module::Indexer)
} | Checks whether the Indexer module is enabled. | indexer_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn rich_indexer_enable(&self) -> bool {
self.modules.contains(&Module::RichIndexer)
} | Checks whether the Rich Indexer module is enabled. | rich_indexer_enable | rust | nervosnetwork/ckb | util/app-config/src/configs/rpc.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/rpc.rs | MIT |
pub fn adjust<P: AsRef<Path>>(&mut self, root_dir: &Path, tx_pool_dir: P) {
_adjust(
root_dir,
tx_pool_dir.as_ref(),
&mut self.persisted_data,
"persisted_data",
);
_adjust(
root_dir,
tx_pool_dir.as_ref(),
&mut self.recent_reject,
"recent_reject",
);
} | Canonicalizes paths in the config options.
If `self.persisted_data` is not set, set it to `data_dir / tx_pool_persisted_data`.
If `self.path` is relative, convert them to absolute path using
`root_dir` as current working directory. | adjust | rust | nervosnetwork/ckb | util/app-config/src/configs/tx_pool.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/tx_pool.rs | MIT |
pub fn adjust<P: AsRef<Path>>(&mut self, root_dir: &Path, indexer_dir: P) {
_adjust(root_dir, indexer_dir.as_ref(), &mut self.store, "store");
_adjust(
root_dir,
indexer_dir.as_ref(),
&mut self.secondary_path,
"secondary_path",
);
_adjust(
root_dir,
indexer_dir.as_ref(),
&mut self.rich_indexer.store,
"sqlite/sqlite.db",
);
} | Canonicalizes paths in the config options.
If `self.store` is not set, set it to `data_dir / indexer / store`.
If `self.secondary_path` is not set, set it to `data_dir / indexer / secondary_path`.
If `self.rich_indexer` is `Sqlite`, and `self.rich_indexer.sqlite.store` is not set,
set it to `data_dir / indexer / sqlite / sqlite.db`.
If any of the above paths is relative, convert them to absolute path using
`root_dir` as current working directory. | adjust | rust | nervosnetwork/ckb | util/app-config/src/configs/indexer.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/indexer.rs | MIT |
pub fn generate_random_key() -> [u8; 32] {
loop {
let mut key: [u8; 32] = [0; 32];
rand::thread_rng().fill(&mut key);
if secio::SecioKeyPair::secp256k1_raw_key(key).is_ok() {
return key;
}
}
} | Generate random secp256k1 key | generate_random_key | rust | nervosnetwork/ckb | util/app-config/src/configs/network.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/network.rs | MIT |
pub fn write_secret_to_file(secret: &[u8], path: PathBuf) -> Result<(), Error> {
fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.and_then(|mut file| {
file.write_all(secret)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(fs::Permissions::from_mode(0o400))
}
#[cfg(not(unix))]
{
let mut permissions = file.metadata()?.permissions();
permissions.set_readonly(true);
file.set_permissions(permissions)
}
})
} | Secret key storage | write_secret_to_file | rust | nervosnetwork/ckb | util/app-config/src/configs/network.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/network.rs | MIT |
pub fn read_secret_key(path: PathBuf) -> Result<Option<secio::SecioKeyPair>, Error> {
let mut file = match fs::File::open(path.clone()) {
Ok(file) => file,
Err(_) => return Ok(None),
};
let warn = |m: bool, d: &str| {
if m {
ckb_logger::warn!(
"Your network secret file's permission is not {}, path: {:?}. \
Please fix it as soon as possible",
d,
path
)
}
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
warn(
file.metadata()?.permissions().mode() & 0o177 != 0,
"less than 0o600",
);
}
#[cfg(not(unix))]
{
warn(!file.metadata()?.permissions().readonly(), "readonly");
}
let mut buf = Vec::new();
file.read_to_end(&mut buf).and_then(|_read_size| {
secio::SecioKeyPair::secp256k1_raw_key(&buf)
.map(Some)
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid secret key data"))
})
} | Load secret key from path | read_secret_key | rust | nervosnetwork/ckb | util/app-config/src/configs/network.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/network.rs | MIT |
pub fn secret_key_path(&self) -> PathBuf {
let mut path = self.path.clone();
path.push("secret_key");
path
} | Gets the network secret key path. | secret_key_path | rust | nervosnetwork/ckb | util/app-config/src/configs/network.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/network.rs | MIT |
pub fn peer_store_path(&self) -> PathBuf {
let mut path = self.path.clone();
path.push("peer_store");
path
} | Gets the peer store path. | peer_store_path | rust | nervosnetwork/ckb | util/app-config/src/configs/network.rs | https://github.com/nervosnetwork/ckb/blob/master/util/app-config/src/configs/network.rs | MIT |
Subsets and Splits