Document more TODOs as tickets (#1418)

Went through the TODOs, removed a bunch, which are outdated or nothing more than a regular comment, documented a bunch more as actual tickets and made them FIXMEs and unified their structure (`FIXME #TICKETNO DESC` for local tickets, `FIXME: DESC LINK` for external tickets) for easier in-editor support. Further more remove unnecessary remarks and related old code that I noticed in that instance.
This commit is contained in:
Benjamin Kampmann
2019-01-30 10:29:48 +01:00
committed by GitHub
parent d2cfd7b9dc
commit 15ae7cfef6
59 changed files with 65 additions and 142 deletions
@@ -16,8 +16,8 @@
//! A consensus proposer for "basic" chains which use the primitive inherent-data.
// FIXME: move this into substrate-consensus-common - https://github.com/paritytech/substrate/issues/1021
// FIXME #1021 move this into substrate-consensus-common
//
use std::{sync::Arc, self};
use log::{info, trace};
@@ -197,7 +197,6 @@ impl<Block, C, A> Proposer<Block, C, A> where
let pending_iterator = self.transaction_pool.ready();
for pending in pending_iterator {
// TODO [ToDr] Probably get rid of it, and validate in runtime.
let encoded_size = pending.data.encode().len();
if pending_size + encoded_size >= MAX_TRANSACTIONS_SIZE { break }
+2 -3
View File
@@ -307,7 +307,6 @@ where Block: BlockT<Hash=H256>,
}
fn reset_storage(&mut self, mut top: StorageMap, children: ChildrenStorageMap) -> Result<H256, client::error::Error> {
// TODO: wipe out existing trie.
if top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) {
return Err(client::error::ErrorKind::GenesisInvalid.into());
@@ -384,7 +383,7 @@ struct DbGenesisStorage(pub H256);
impl DbGenesisStorage {
pub fn new() -> Self {
let mut root = H256::default();
let mut mdb = MemoryDB::<Blake2Hasher>::default(); // TODO: use new() to make it more correct
let mut mdb = MemoryDB::<Blake2Hasher>::default();
state_machine::TrieDBMut::<Blake2Hasher>::new(&mut mdb, &mut root);
DbGenesisStorage(root)
}
@@ -1024,7 +1023,7 @@ mod tests {
fn prepare_changes(changes: Vec<(Vec<u8>, Vec<u8>)>) -> (H256, MemoryDB<Blake2Hasher>) {
let mut changes_root = H256::default();
let mut changes_trie_update = MemoryDB::<Blake2Hasher>::default(); // TODO: change to new() to make more correct
let mut changes_trie_update = MemoryDB::<Blake2Hasher>::default();
{
let mut trie = TrieDBMut::<Blake2Hasher>::new(
&mut changes_trie_update,
-2
View File
@@ -341,7 +341,6 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
// update block number to hash lookup entries.
for retracted in tree_route.retracted() {
if retracted.hash == meta.finalized_hash {
// TODO: can we recover here?
warn!("Safety failure: reverting finalized block {:?}",
(&retracted.number, &retracted.hash));
}
@@ -438,7 +437,6 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
fn finalize_header(&self, id: BlockId<Block>) -> ClientResult<()> {
if let Some(header) = self.header(id)? {
let mut transaction = DBTransaction::new();
// TODO: ensure best chain contains this block.
let hash = header.hash();
let number = *header.number();
self.note_finalized(&mut transaction, &header, hash.clone())?;
@@ -45,7 +45,7 @@ pub type SharedCache<B, H> = Arc<Mutex<Cache<B, H>>>;
/// Create new shared cache instance with given max memory usage.
pub fn new_shared_cache<B: Block, H: Hasher>(shared_cache_size: usize) -> SharedCache<B, H> {
let cache_items = shared_cache_size / 100; // Estimated average item size. TODO: more accurate tracking
let cache_items = shared_cache_size / 100; // Guestimate, potentially inaccurate
Arc::new(Mutex::new(Cache {
storage: LruCache::new(cache_items),
hashes: LruCache::new(cache_items),
@@ -205,7 +205,6 @@ where
native_call: Option<NC>,
) -> Result<NativeOrEncoded<R>, error::Error> where ExecutionManager<EM>: Clone {
let state = self.backend.state_at(*at)?;
//TODO: Find a better way to prevent double block initialization
if method != "Core_initialise_block" && initialised_block.map(|id| id != *at).unwrap_or(true) {
let header = prepare_environment_block()?;
state_machine::execute_using_consensus_failure_handler::<
+6 -14
View File
@@ -130,7 +130,6 @@ pub trait BlockBody<Block: BlockT> {
}
/// Client info
// TODO: split queue info from chain info and amalgamate into single struct.
#[derive(Debug)]
pub struct ClientInfo<Block: BlockT> {
/// Best block hash.
@@ -325,7 +324,6 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// Get the RuntimeVersion at a given block.
pub fn runtime_version_at(&self, id: &BlockId<Block>) -> error::Result<RuntimeVersion> {
// TODO: Post Poc-2 return an error if version is missing
self.executor.runtime_version(id)
}
@@ -738,11 +736,9 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
self.apply_finality_with_block_hash(operation, parent_hash, None, last_best, make_notifications)?;
}
// TODO: correct path logic for when to execute this function
// https://github.com/paritytech/substrate/issues/1232
// FIXME #1232: correct path logic for when to execute this function
let (storage_update,changes_update,storage_changes) = self.block_execution(&operation.op, &import_headers, origin, hash, body.clone())?;
// TODO: non longest-chain rule.
let is_new_best = finalized || match fork_choice {
ForkChoiceStrategy::LongestChain => import_headers.post().number() > &last_best_number,
ForkChoiceStrategy::Custom(v) => v,
@@ -880,7 +876,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
// if the block is not a direct ancestor of the current best chain,
// then some other block is the common ancestor.
if route_from_best.common_block().hash != block {
// TODO: reorganize best block to be the best chain containing
// FIXME: #1442 reorganize best block to be the best chain containing
// `block`.
}
@@ -1020,7 +1016,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// Get block status.
pub fn block_status(&self, id: &BlockId<Block>) -> error::Result<BlockStatus> {
// TODO: more efficient implementation
// this can probably be implemented more efficiently
if let BlockId::Hash(ref h) = id {
if self.importing_block.read().as_ref().map_or(false, |importing| h == importing) {
return Ok(BlockStatus::Queued);
@@ -1073,10 +1069,9 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// If `maybe_max_block_number` is `Some(max_block_number)`
/// the search is limited to block `numbers <= max_block_number`.
/// in other words as if there were no blocks greater `max_block_number`.
///
/// TODO [snd] possibly implement this on blockchain::Backend and just redirect here
/// TODO : we want to move this implement to `blockchain::Backend`, see [#1443](https://github.com/paritytech/substrate/issues/1443)
/// Returns `Ok(None)` if `target_hash` is not found in search space.
/// TODO [snd] write down time complexity
/// TODO: document time complexity of this, see [#1444](https://github.com/paritytech/substrate/issues/1444)
pub fn best_containing(&self, target_hash: Block::Hash, maybe_max_number: Option<NumberFor<Block>>)
-> error::Result<Option<Block::Hash>>
{
@@ -1140,7 +1135,6 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
// waiting until we are <= max_number
if let Some(max_number) = maybe_max_number {
loop {
// TODO [snd] this should be a panic
let current_header = self.backend.blockchain().header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| error::Error::from(format!("failed to get header for hash {}", current_hash)))?;
@@ -1160,7 +1154,6 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
return Ok(Some(best_hash));
}
// TODO [snd] this should be a panic
let current_header = self.backend.blockchain().header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| error::Error::from(format!("failed to get header for hash {}", current_hash)))?;
@@ -1176,8 +1169,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
// header may be on a dead fork -- the only leaves that are considered are
// those which can still be finalized.
//
// TODO: only issue this warning when not on a dead fork
// part of https://github.com/paritytech/substrate/issues/1558
// FIXME #1558 only issue this warning when not on a dead fork
warn!(
"Block {:?} exists in chain but not found when following all \
leaves backwards. Number limit = {:?}",
@@ -141,7 +141,7 @@ impl<S, F, Block> BlockchainHeaderBackend<Block> for Blockchain<S, F> where Bloc
impl<S, F, Block> BlockchainBackend<Block> for Blockchain<S, F> where Block: BlockT, S: Storage<Block>, F: Fetcher<Block> {
fn body(&self, _id: BlockId<Block>) -> ClientResult<Option<Vec<Block::Extrinsic>>> {
// TODO [light]: fetch from remote node
// TODO: #1445 fetch from remote node
Ok(None)
}
+3 -4
View File
@@ -392,7 +392,7 @@ enum CheckedHeader<H> {
/// check a header has been signed by the right key. If the slot is too far in the future, an error will be returned.
/// if it's successful, returns the pre-header, the slot number, and the signat.
//
// FIXME: needs misbehavior types - https://github.com/paritytech/substrate/issues/1018
// FIXME #1018 needs misbehavior types
fn check_header<B: Block>(slot_now: u64, mut header: B::Header, hash: B::Hash, authorities: &[Ed25519AuthorityId])
-> Result<CheckedHeader<B::Header>, String>
where DigestItemFor<B>: CompatibleDigestItem
@@ -537,8 +537,7 @@ impl<B: Block, C, E> Verifier<B> for AuraVerifier<C, E> where
);
// we add one to allow for some small drift.
// FIXME: in the future, alter this queue to allow deferring of headers
// https://github.com/paritytech/substrate/issues/1019
// FIXME #1019 in the future, alter this queue to allow deferring of headers
let checked_header = check_header::<B>(slot_now + 1, header, hash, &authorities[..])?;
match checked_header {
CheckedHeader::Checked(pre_header, slot_num, sig) => {
@@ -577,7 +576,7 @@ impl<B: Block, C, E> Verifier<B> for AuraVerifier<C, E> where
fork_choice: ForkChoiceStrategy::LongestChain,
};
// FIXME: extract authorities - https://github.com/paritytech/substrate/issues/1019
// FIXME #1019 extract authorities
Ok((import_block, None))
}
CheckedHeader::Deferred(a, b) => {
@@ -401,7 +401,7 @@ pub fn import_single_block<B: BlockT, V: Verifier<B>>(
} else {
debug!(target: "sync", "Header {} was not provided ", block.hash);
}
return Err(BlockImportError::IncompleteHeader(peer)) //TODO: use persistent ID
return Err(BlockImportError::IncompleteHeader(peer))
},
};
@@ -441,7 +441,7 @@ pub fn import_single_block<B: BlockT, V: Verifier<B>>(
},
Ok(ImportResult::KnownBad) => {
debug!(target: "sync", "Peer gave us a bad block {}: {:?}", number, hash);
Err(BlockImportError::BadBlock(peer)) //TODO: use persistent ID
Err(BlockImportError::BadBlock(peer))
},
Err(e) => {
debug!(target: "sync", "Error importing block {}: {:?}: {:?}", number, hash, e);
+3 -6
View File
@@ -31,7 +31,7 @@
//! set for this block height.
#![cfg(feature="rhd")]
// FIXME: doesn't compile - https://github.com/paritytech/substrate/issues/1020
// FIXME #1020 doesn't compile
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -432,7 +432,6 @@ impl<B, P, I, InStream, OutSink> Drop for BftFuture<B, P, I, InStream, OutSink>
OutSink: Sink<SinkItem=Communication<B>, SinkError=Error>,
{
fn drop(&mut self) {
// TODO: have a trait member to pass misbehavior reports into.
let misbehavior = self.inner.drain_misbehavior().collect::<Vec<_>>();
self.inner.context().proposer.import_misbehavior(misbehavior);
}
@@ -466,7 +465,7 @@ pub struct BftService<B: Block, P, I> {
live_agreement: Mutex<Option<(B::Header, AgreementHandle)>>,
round_cache: Arc<Mutex<RoundCache<B::Hash>>>,
round_timeout_multiplier: u64,
key: Arc<ed25519::Pair>, // TODO: key changing over time.
key: Arc<ed25519::Pair>,
factory: P,
}
@@ -488,14 +487,13 @@ impl<B, P, I> BftService<B, P, I>
start_round: 0,
})),
round_timeout_multiplier: 10,
key: key, // TODO: key changing over time.
key: key,
factory,
}
}
/// Get the local Authority ID.
pub fn local_id(&self) -> AuthorityId {
// TODO: based on a header and some keystore.
self.key.public().into()
}
@@ -1084,7 +1082,6 @@ impl<C, A> BaseProposer<<C as AuthoringApi>::Block> for Proposer<C, A> where
self.transaction_pool.ready(|pending_iterator| {
let mut pending_size = 0;
for pending in pending_iterator {
// TODO [ToDr] Probably get rid of it, and validate in runtime.
let encoded_size = pending.data.encode().len();
if pending_size + encoded_size >= MAX_TRANSACTIONS_SIZE { break }
@@ -268,7 +268,6 @@ macro_rules! native_executor_instance {
native_executor_instance!(IMPL $name, $dispatcher, $version, $code);
};
(IMPL $name:ident, $dispatcher:path, $version:path, $code:expr) => {
// TODO: this is not so great I think I should go back to have dispatch take a type param and modify this macro to accept a type param and then pass it in from the test-client instead
use primitives::Blake2Hasher as _Blake2Hasher;
impl $crate::NativeExecutionDispatch for $name {
fn native_equivalent() -> &'static [u8] {
@@ -118,7 +118,6 @@ impl ReadPrimitive<u32> for MemoryInstance {
}
}
// TODO: this macro does not support `where` clauses and that seems somewhat tricky to add
impl_function_executor!(this: FunctionExecutor<'e, E>,
ext_print_utf8(utf8_data: *const u8, utf8_len: u32) => {
if let Ok(utf8) = this.memory.get(utf8_data, utf8_len as usize) {
+1 -2
View File
@@ -577,7 +577,6 @@ impl<B, E, Block: BlockT<Hash=H256>, N, RA> voter::Environment<Block::Hash, Numb
let prevote_timer = Delay::new(now + self.config.gossip_duration * 2);
let precommit_timer = Delay::new(now + self.config.gossip_duration * 4);
// TODO: dispatch this with `mpsc::spawn`.
let incoming = ::communication::checked_message_stream::<Block, _>(
round,
self.set_id,
@@ -857,7 +856,7 @@ fn finalize_block<B, Block: BlockT<Hash=H256>, E, RA>(
// lock must be held through writing to DB to avoid race
let mut authority_set = authority_set.inner().write();
// TODO [andre]: clone only when changed (#1483)
// FIXME #1483: clone only when changed
let old_authority_set = authority_set.clone();
// needed in case there is an authority set change, used for reverting in
// case of error
+1 -1
View File
@@ -58,7 +58,7 @@ pub struct InvalidPassword;
struct EncryptedKey {
mac: [u8; 32],
salt: [u8; 32],
ciphertext: Vec<u8>, // TODO: switch to fixed-size when serde supports
ciphertext: Vec<u8>, // FIXME: switch to fixed-size when serde supports
iv: [u8; 16],
iterations: u32,
}
@@ -76,7 +76,6 @@ impl<B: BlockT> ConsensusGossip<B> {
if roles.intersects(Roles::AUTHORITY) {
trace!(target:"gossip", "Registering {:?} {}", roles, who);
// Send out all known messages to authorities.
// TODO: limit by size
let mut known_messages = HashSet::new();
for entry in self.messages.iter() {
known_messages.insert((entry.topic, entry.message_hash));
+1 -1
View File
@@ -213,7 +213,7 @@ impl<B, E> OnDemandService<B> for OnDemand<B, E> where
B::Header: HeaderT,
{
fn on_connect(&self, peer: NodeIndex, role: Roles, best_number: NumberFor<B>) {
if !role.intersects(Roles::FULL | Roles::AUTHORITY) { // TODO: correct?
if !role.intersects(Roles::FULL | Roles::AUTHORITY) {
return;
}
-2
View File
@@ -458,7 +458,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
message::FromBlock::Number(n) => BlockId::Number(n),
};
let max = cmp::min(request.max.unwrap_or(u32::max_value()), MAX_BLOCK_DATA_RESPONSE) as usize;
// TODO: receipts, etc.
let get_header = request.fields.contains(message::BlockAttributes::HEADER);
let get_body = request.fields.contains(message::BlockAttributes::BODY);
let get_justification = request.fields.contains(message::BlockAttributes::JUSTIFICATION);
@@ -498,7 +497,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
}
fn on_block_response(&self, io: &mut SyncIo, peer: NodeIndex, request: message::BlockRequest<B>, response: message::BlockResponse<B>) {
// TODO: validate response
let blocks_range = match (
response.blocks.first().and_then(|b| b.header.as_ref().map(|h| h.number())),
response.blocks.last().and_then(|b| b.header.as_ref().map(|h| h.number())),
@@ -49,7 +49,7 @@ impl ChangesTrieConfiguration {
return 1;
}
// TODO: use saturating_pow when available
// FIXME: use saturating_pow once stabilized - https://github.com/rust-lang/rust/issues/48320
let mut max_digest_interval = self.digest_interval;
for _ in 1..self.digest_levels {
max_digest_interval = match max_digest_interval.checked_mul(self.digest_interval) {
-16
View File
@@ -238,16 +238,6 @@ impl Pair {
r.copy_from_slice(pk);
Public(r)
}
/// Derive a child key. Probably unsafe and broken.
// TODO: proper HD derivation https://cardanolaunch.com/assets/Ed25519_BIP.pdf
pub fn derive_child_probably_bad(&self, chain_data: &[u8]) -> Pair {
let sig = self.sign(chain_data);
let mut seed = [0u8; 32];
seed.copy_from_slice(&sig[..32]);
Pair::from_seed(&seed)
}
}
/// Verify a signature on a message. Returns true if the signature is good.
@@ -350,12 +340,6 @@ mod test {
assert_eq!(pair1.public(), pair2.public());
}
#[test]
fn derive_child() {
let pair = Pair::generate();
let _pair2 = pair.derive_child_probably_bad(b"session_1234");
}
#[test]
fn ss58check_roundtrip_works() {
let pair = Pair::from_seed(b"12345678901234567890123456789012");
+2 -1
View File
@@ -41,7 +41,8 @@ impl<Number: traits::As<u64>> NumberOrHex<Number> {
match self {
NumberOrHex::Number(n) => Ok(n),
NumberOrHex::Hex(h) => {
// TODO [ToDr] this only supports `u64` since `BlockNumber` is `As<u64>` we could possibly go with `u128`. (#1377)
// FIXME #1377 this only supports `u64` since `BlockNumber`
// is `As<u64>` we could possibly go with `u128`.
let l = h.low_u64();
if U256::from(l) != h {
Err(format!("`{}` does not fit into the block number type.", h))
+1 -1
View File
@@ -106,7 +106,7 @@ pub fn import_blocks<F, E, R>(
impl<B: Block> Link<B> for DummyLink { }
let client = new_client::<F>(&config)?;
// FIXME: this shouldn't need a mutable config. https://github.com/paritytech/substrate/issues/1134
// FIXME #1134 this shouldn't need a mutable config.
let queue = components::FullComponents::<F>::build_import_queue(&mut config, client.clone())?;
queue.start(DummyLink)?;
+1 -2
View File
@@ -217,7 +217,6 @@ impl<C: Components> MaintainTransactionPool<Self> for C where
ComponentClient<C>: ProvideRuntimeApi,
<ComponentClient<C> as ProvideRuntimeApi>::Api: TaggedTransactionQueue<ComponentBlock<C>>,
{
// TODO [ToDr] Optimize and re-use tags from the pool.
fn on_block_imported(
id: &BlockId<ComponentBlock<C>>,
client: &ComponentClient<C>,
@@ -329,7 +328,7 @@ pub trait Components: Sized + 'static {
type RuntimeApi: Send + Sync;
/// A type that can start the RPC.
type RPC: StartRPC<Self>;
// TODO [ToDr] Traitify transaction pool and allow people to implement their own. (#1242)
// TODO: Traitify transaction pool and allow people to implement their own. (#1242)
/// A type that can maintain transaction pool.
type TransactionPool: MaintainTransactionPool<Self>;
/// Extrinsic pool type.
+1 -2
View File
@@ -137,7 +137,7 @@ impl<Components: components::Components> Service<Components> {
let mut keystore = Keystore::open(config.keystore_path.as_str().into())?;
// This is meant to be for testing only
// FIXME: remove this - https://github.com/paritytech/substrate/issues/1063
// FIXME #1063 remove this
for seed in &config.keys {
keystore.generate_from_seed(seed)?;
}
@@ -274,7 +274,6 @@ impl<Components: components::Components> Service<Components> {
// extrinsic notifications
let network = Arc::downgrade(&network);
let events = transaction_pool.import_notification_stream()
// TODO [ToDr] Consider throttling?
.for_each(move |_| {
if let Some(network) = network.upgrade() {
network.trigger_repropagate();
-1
View File
@@ -41,7 +41,6 @@ use primitives::hexdisplay::HexDisplay;
use primitives::H256;
use hash_db::Hasher;
// TODO: use the real error, not NoError.
environmental!(ext: trait Externalities<Blake2Hasher>);
-4
View File
@@ -315,8 +315,6 @@ pub fn trie_root<
B: AsRef<[u8]>,
>(_input: I) -> [u8; 32] {
unimplemented!()
// TODO Maybe implement (though probably easier/cleaner to have blake2 be the only thing
// implemneted natively and compile the trie logic as wasm).
}
/// A trie root formed from the enumerated items.
@@ -326,8 +324,6 @@ pub fn ordered_trie_root<
A: AsRef<[u8]>
>(_input: I) -> [u8; 32] {
unimplemented!()
// TODO Maybe implement (though probably easier/cleaner to have blake2 be the only thing
// implemneted natively and compile the trie logic as wasm).
}
/// The current relay chain identifier.
@@ -156,7 +156,6 @@ impl<Address: Codec, Index: HasCompact + Codec, Signature: Codec, Call: Encode>
}
}
/// TODO: use derive when possible.
#[cfg(feature = "std")]
impl<Address, Index, Signature, Call> fmt::Debug
for UncheckedExtrinsic<Address, Index, Call, Signature>
@@ -168,7 +168,6 @@ impl<Address: Encode, Index, Signature: Encode, Call: Encode> serde::Serialize
}
}
/// TODO: use derive when possible.
#[cfg(feature = "std")]
impl<Address, Index, Call, Signature> fmt::Debug for UncheckedMortalCompactExtrinsic<Address, Index, Call, Signature> where
Address: fmt::Debug,
@@ -166,7 +166,6 @@ impl<Address: Encode, Index: Encode, Signature: Encode, Call: Encode> serde::Ser
}
}
/// TODO: use derive when possible.
#[cfg(feature = "std")]
impl<Address, Index, Call, Signature> fmt::Debug for UncheckedMortalExtrinsic<Address, Index, Call, Signature> where
Address: fmt::Debug,
-1
View File
@@ -579,7 +579,6 @@ mod tests {
pub enum RawLog<AuthorityId> { B1(AuthorityId), B2(AuthorityId) }
}
// TODO try to avoid redundant brackets: a(AuthoritiesChange), b
impl_outer_log! {
pub enum Log(InternalLog: DigestItem<H256, u64>) for Runtime {
a(AuthoritiesChange), b()
+1 -1
View File
@@ -220,7 +220,7 @@ impl<BlockHash: Hash, Key: Hash> NonCanonicalOverlay<BlockHash, Key> {
commit.data.inserted = self.last_canonicalized_overlay.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
commit.data.deleted = overlay.deleted;
} else {
// TODO: borrow checker won't allow us to split out mutable references
// borrow checker won't allow us to split out mutable references
// required for recursive processing. A more efficient implementation
// that does not require converting to vector is possible
let mut vec: Vec<_> = self.levels.drain(..).collect();
+2 -2
View File
@@ -118,7 +118,7 @@ impl<H: Hasher> Consolidate for MemoryDB<H> {
}
/// Error impossible.
// TODO: use `!` type when stabilized.
// FIXME: use `!` type when stabilized. https://github.com/rust-lang/rust/issues/35121
#[derive(Debug)]
pub enum Void {}
@@ -291,7 +291,7 @@ impl<H: Hasher> Backend<H> for InMemory<H> where H::Out: HeapSizeOf {
}
fn try_into_trie_backend(self) -> Option<TrieBackend<Self::TrieBackendStorage, H>> {
let mut mdb = MemoryDB::default(); // TODO: should be more correct and use ::new()
let mut mdb = MemoryDB::default();
let mut root = None;
for (storage_key, map) in self.inner {
if storage_key != None {
@@ -104,7 +104,7 @@ pub fn key_changes_proof_check<S: RootsStorage<H>, H: Hasher>(
max: u64,
key: &[u8]
) -> Result<Vec<(u64, u32)>, String> where H::Out: HeapSizeOf {
let mut proof_db = MemoryDB::<H>::default(); // TODO: use new for correctness
let mut proof_db = MemoryDB::<H>::default();
for item in proof {
proof_db.insert(&item);
}
@@ -62,7 +62,7 @@ pub fn prune<S: Storage<H>, H: Hasher, F: FnMut(H::Out)>(
};
// delete changes trie for every block in range
// TODO: limit `max_digest_interval` so that this cycle won't involve huge ranges
// FIXME: limit `max_digest_interval` so that this cycle won't involve huge ranges
for block in first..last+1 {
let root = match storage.root(current_block, block) {
Ok(Some(root)) => root,
+1 -1
View File
@@ -302,7 +302,7 @@ where
);
let root_and_tx = root_and_tx.map(|(root, changes)| {
let mut calculated_root = Default::default();
let mut mdb = MemoryDB::default(); // TODO: use new for correctness
let mut mdb = MemoryDB::default();
{
let mut trie = TrieDBMut::<H>::new(&mut mdb, &mut calculated_root);
for (key, value) in changes {
@@ -195,7 +195,7 @@ where
H: Hasher,
H::Out: HeapSizeOf,
{
let mut db = MemoryDB::default(); // TODO: use new for correctness
let mut db = MemoryDB::default();
for item in proof {
db.insert(&item);
}
@@ -82,7 +82,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> Backend<H> for TrieBackend<S, H> where
}
fn pairs(&self) -> Vec<(Vec<u8>, Vec<u8>)> {
let mut read_overlay = MemoryDB::default(); // TODO: use new for correctness
let mut read_overlay = MemoryDB::default();
let eph = Ephemeral::new(self.essence.backend_storage(), &mut read_overlay);
let collect_all = || -> Result<_, Box<TrieError<H::Out>>> {
@@ -106,7 +106,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> Backend<H> for TrieBackend<S, H> where
}
fn keys(&self, prefix: &Vec<u8>) -> Vec<Vec<u8>> {
let mut read_overlay = MemoryDB::default(); // TODO: use new for correctness
let mut read_overlay = MemoryDB::default();
let eph = Ephemeral::new(self.essence.backend_storage(), &mut read_overlay);
let collect_all = || -> Result<_, Box<TrieError<H::Out>>> {
@@ -193,7 +193,7 @@ pub mod tests {
fn test_db() -> (MemoryDB<Blake2Hasher>, H256) {
let mut root = H256::default();
let mut mdb = MemoryDB::<Blake2Hasher>::default(); // TODO: use new() to be more correct
let mut mdb = MemoryDB::<Blake2Hasher>::default();
{
let mut trie = TrieDBMut::new(&mut mdb, &mut root);
trie.insert(b"key", b"value").expect("insert failed");
@@ -230,7 +230,7 @@ pub mod tests {
#[test]
fn pairs_are_empty_on_empty_storage() {
assert!(TrieBackend::<MemoryDB<Blake2Hasher>, Blake2Hasher>::new(
MemoryDB::default(), // TODO: use new() to be more correct
MemoryDB::default(),
Default::default(),
).pairs().is_empty());
}
@@ -176,7 +176,7 @@ impl<'a,
where H::Out: HeapSizeOf
{
fn keys(&self) -> HashMap<H::Out, i32> {
self.overlay.keys() // TODO: iterate backing
self.overlay.keys()
}
fn get(&self, key: &H::Out) -> Option<DBValue> {
+1 -1
View File
@@ -49,7 +49,7 @@ use keyring::Keyring;
mod local_executor {
#![allow(missing_docs)]
use super::runtime;
// TODO: change the macro and pass in the `BlakeHasher` that dispatch needs from here instead
// FIXME #1576 change the macro and pass in the `BlakeHasher` that dispatch needs from here instead
native_executor_instance!(
pub LocalExecutor,
runtime::api::dispatch,
@@ -20,9 +20,6 @@
//! and their priority.
//! The pool is able to return an iterator that traverses transaction
//! graph in the correct order taking into account priorities and dependencies.
//!
//! TODO [ToDr]
//! - [ ] Multi-threading (getting ready transactions should not block the pool)
#![warn(missing_docs)]
#![warn(unused_extern_crates)]
@@ -307,7 +307,6 @@ impl<B: ChainApi> Pool<B> {
impl<B: ChainApi> Pool<B> {
/// Create a new transaction pool.
/// TODO [ToDr] Options
pub fn new(_options: Options, api: B) -> Self {
Pool {
api,
@@ -67,7 +67,6 @@ impl<T, Block> txpool::ChainApi for ChainApi<T, Block> where
Ok(self.client.runtime_api().validate_transaction(at, uxt)?)
}
// TODO [toDr] Use proper lbock number type
fn block_id_to_number(&self, at: &BlockId<Self::Block>) -> error::Result<Option<txpool::NumberFor<Self>>> {
Ok(self.client.block_number_from_id(at)?)
}
+3 -3
View File
@@ -16,7 +16,7 @@
//! Utility functions to interact with Substrate's Base-16 Modified Merkle Patricia tree ("trie").
// TODO: no_std
// FIXME: no_std - https://github.com/paritytech/substrate/issues/1574
mod error;
mod node_header;
@@ -71,7 +71,7 @@ pub fn delta_trie_root<H: Hasher, I, A, B>(db: &mut HashDB<H>, mut root: H::Out,
for (key, change) in delta {
match change {
Some(val) => trie.insert(key.as_ref(), val.as_ref())?,
None => trie.remove(key.as_ref())?, // TODO: archive mode
None => trie.remove(key.as_ref())?,
};
}
}
@@ -151,7 +151,7 @@ pub fn child_delta_trie_root<H: Hasher, I, A, B>(_storage_key: &[u8], db: &mut H
for (key, change) in delta {
match change {
Some(val) => trie.insert(key.as_ref(), val.as_ref())?,
None => trie.remove(key.as_ref())?, // TODO: archive mode
None => trie.remove(key.as_ref())?,
};
}
}
+2 -2
View File
@@ -95,14 +95,14 @@ impl<H: Hasher> trie_db::NodeCodec<H> for NodeCodec<H> {
vec![EMPTY_TRIE]
}
// TODO: refactor this so that `partial` isn't already encoded with HPE. Should just be an `impl Iterator<Item=u8>`.
// FIXME: refactor this so that `partial` isn't already encoded with HPE. Should just be an `impl Iterator<Item=u8>`.
fn leaf_node(partial: &[u8], value: &[u8]) -> Vec<u8> {
let mut output = partial_to_key(partial, LEAF_NODE_OFFSET, LEAF_NODE_BIG);
value.encode_to(&mut output);
output
}
// TODO: refactor this so that `partial` isn't already encoded with HPE. Should just be an `impl Iterator<Item=u8>`.
// FIXME: refactor this so that `partial` isn't already encoded with HPE. Should just be an `impl Iterator<Item=u8>`.
fn ext_node(partial: &[u8], child: ChildReference<H::Out>) -> Vec<u8> {
let mut output = partial_to_key(partial, EXTENSION_NODE_OFFSET, EXTENSION_NODE_BIG);
match child {
-9
View File
@@ -67,34 +67,25 @@ impl trie_root::TrieStream for TrieStream {
fn append_leaf(&mut self, key: &[u8], value: &[u8]) {
self.buffer.extend(fuse_nibbles_node(key, true));
// OPTIMISATION: I'd like to do `hpe.encode_to(&mut self.buffer);` here; need an `impl<'a> Encode for impl Iterator<Item = u8> + 'a`?
value.encode_to(&mut self.buffer);
}
fn begin_branch(&mut self, maybe_value: Option<&[u8]>, has_children: impl Iterator<Item = bool>) {
// println!("[begin_branch] pushing BRANCH_NODE");
self.buffer.extend(&branch_node(maybe_value.is_some(), has_children));
// Push the value if one exists.
if let Some(value) = maybe_value {
value.encode_to(&mut self.buffer);
}
// println!("[begin_branch] buffer so far: {:#x?}", self.buffer);
}
fn append_extension(&mut self, key: &[u8]) {
self.buffer.extend(fuse_nibbles_node(key, false));
}
fn append_substream<H: Hasher>(&mut self, other: Self) {
let data = other.out();
// println!("[append_substream] START own buffer: {:x?}", self.buffer);
// println!("[append_substream] START other buffer: {:x?}", data);
match data.len() {
0...31 => {
// println!("[append_substream] appending data, because data.len() = {}", data.len());
data.encode_to(&mut self.buffer)
},
_ => {
// println!("[append_substream] would have hashed, because data.len() = {}", data.len());
// data.encode_to(&mut self.buffer)
// TODO: re-enable hashing before merging
H::hash(&data).as_ref().encode_to(&mut self.buffer)
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
GenesisConfig {
consensus: Some(ConsensusConfig {
code: include_bytes!("../../runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm").to_vec(), // TODO change
code: include_bytes!("../../runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm").to_vec(), // FIXME change once we have #1252
authorities: initial_authorities.clone(),
}),
system: None,
+2 -3
View File
@@ -46,8 +46,7 @@ construct_simple_protocol! {
/// Node specific configuration
pub struct NodeConfig<F: substrate_service::ServiceFactory> {
/// grandpa connection to import block
// FIXME: rather than putting this on the config, let's have an actual intermediate setup state
// https://github.com/paritytech/substrate/issues/1134
// FIXME #1134 rather than putting this on the config, let's have an actual intermediate setup state
pub grandpa_import_setup: Option<(Arc<grandpa::BlockImportForService<F>>, grandpa::LinkHalfForService<F>)>,
inherent_data_providers: InherentDataProviders,
}
@@ -106,7 +105,7 @@ construct_service_factory! {
executor.spawn(grandpa::run_grandpa(
grandpa::Config {
local_key,
// FIXME: make this available through chainspec?
// FIXME #1578 make this available through chainspec
gossip_duration: Duration::new(4, 0),
justification_period: 4096,
name: Some(service.config.name.clone())
-1
View File
@@ -201,7 +201,6 @@ decl_module! {
/// Report some misbehaviour.
fn report_misbehavior(origin, _report: Vec<u8>) {
ensure_signed(origin)?;
// TODO: requires extension trait.
}
/// Note the previous block's validator missed their opportunity to propose a block.
-4
View File
@@ -347,12 +347,8 @@ decl_storage! {
}
}
// TODO: consider storing upper-bound for contract's gas limit in fixed-length runtime
// code in contract itself and use that.
/// The storage items associated with an account/key.
///
/// TODO: keys should also be able to take AsRef<KeyType> to ensure Vec<u8>s can be passed as &[u8]
pub(crate) struct StorageOf<T>(rstd::marker::PhantomData<T>);
impl<T: Trait> StorageDoubleMap for StorageOf<T> {
const PREFIX: &'static [u8] = b"con:sto:";
@@ -196,8 +196,6 @@ fn write_sandbox_memory<T: Trait>(
// * AFTER MAKING A CHANGE MAKE SURE TO UPDATE COMPLEXITY.MD *
// ***********************************************************
// TODO: ext_balance, ext_address, ext_callvalue, etc.
// Define a function `fn init_env<E: Ext>() -> HostFunctionSet<E>` that returns
// a function set which can be imported by an executed contract.
define_env!(Env, <E: Ext>,
+2 -2
View File
@@ -181,7 +181,7 @@ decl_module! {
/// Report some misbehaviour.
fn report_misbehavior(origin, _report: Vec<u8>) {
ensure_signed(origin)?;
// TODO: https://github.com/paritytech/substrate/issues/1112
// FIXME: https://github.com/paritytech/substrate/issues/1112
}
fn on_finalise(block_number: T::BlockNumber) {
@@ -259,7 +259,7 @@ impl<T: Trait> Module<T> where Ed25519AuthorityId: core::convert::From<<T as Tra
/// sets should be.
pub struct SyncedAuthorities<T>(::rstd::marker::PhantomData<T>);
// TODO: remove when https://github.com/rust-lang/rust/issues/26925 is fixed
// FIXME: remove when https://github.com/rust-lang/rust/issues/26925 is fixed
impl<T> Default for SyncedAuthorities<T> {
fn default() -> Self {
SyncedAuthorities(::rstd::marker::PhantomData)
+2 -2
View File
@@ -138,7 +138,7 @@ decl_storage! {
impl<T: Trait> Module<T> {
/// The number of validators currently.
pub fn validator_count() -> u32 {
<Validators<T>>::get().len() as u32 // TODO: can probably optimised
<Validators<T>>::get().len() as u32
}
/// The last length change, if there was one, zero if not.
@@ -158,7 +158,7 @@ impl<T: Trait> Module<T> {
/// Called by `staking::new_era()` only. `next_session` should be called after this in order to
/// update the session keys to the next validator set.
pub fn set_validators(new: &[T::AccountId]) {
<Validators<T>>::put(&new.to_vec()); // TODO: optimise.
<Validators<T>>::put(&new.to_vec());
<consensus::Module<T>>::set_authorities(
&new.iter().cloned().map(T::ConvertAccountIdToSessionKey::convert).collect::<Vec<_>>()
);
+3 -3
View File
@@ -355,7 +355,7 @@ impl<T: Trait> Module<T> {
let noms = Self::current_nominators_for(v);
let total = noms.iter().map(<balances::Module<T>>::total_balance).fold(T::Balance::zero(), |acc, x| acc + x);
if !total.is_zero() {
let safe_mul_rational = |b| b * rem / total;// TODO: avoid overflow
let safe_mul_rational = |b| b * rem / total;// FIXME #1572 avoid overflow
for n in noms.iter() {
let _ = <balances::Module<T>>::slash(n, safe_mul_rational(<balances::Module<T>>::total_balance(n))); // best effort - not much that can be done on fail.
}
@@ -376,7 +376,7 @@ impl<T: Trait> Module<T> {
.map(<balances::Module<T>>::total_balance)
.fold(<balances::Module<T>>::total_balance(who), |acc, x| acc + x)
.max(One::one());
let safe_mul_rational = |b| b * reward / total;// TODO: avoid overflow
let safe_mul_rational = |b| b * reward / total;// FIXME #1572: avoid overflow
for n in noms.iter() {
let _ = <balances::Module<T>>::reward(n, safe_mul_rational(<balances::Module<T>>::total_balance(n)));
}
@@ -454,7 +454,7 @@ impl<T: Trait> Module<T> {
// combination of validators, then use session::internal::set_validators().
// for now, this just orders would-be stakers by their balances and chooses the top-most
// <ValidatorCount<T>>::get() of them.
// TODO: this is not sound. this should be moved to an off-chain solution mechanism.
// FIXME #1571 this is not sound. this should be moved to an off-chain solution mechanism.
let mut intentions = Self::intentions()
.into_iter()
.map(|v| (Self::slashable_balance(&v), v))
-1
View File
@@ -416,7 +416,6 @@ fn nominating_slashes_should_work() {
assert_eq!(Balances::total_balance(&2), 20); //not slashed
assert_eq!(Balances::total_balance(&3), 10); //slashed
assert_eq!(Balances::total_balance(&4), 30); //slashed
// TODO: change slash % to something sensible.
});
}
@@ -74,7 +74,7 @@ struct AddExtraGenesisLine {
pub extra_field: ext::Parens<Ident>,
pub coldot_token: Token![:],
pub extra_type: syn::Type,
// TODO use a custom ext::Option instead (syn option on '=' fails)
// FIXME #1570: use a custom ext::Option instead (syn option on '=' fails)
pub default_value: ext::Seq<DeclStorageDefault>,
}
@@ -91,7 +91,7 @@ struct DeclStorageLine {
pub build: Option<DeclStorageBuild>,
pub coldot_token: Token![:],
pub storage_type: DeclStorageType,
// TODO use a custom ext::Option instead (syn option on '=' fails)
// FIXME #1570: use a custom ext::Option instead (syn option on '=' fails)
pub default_value: ext::Seq<DeclStorageDefault>,
}
@@ -57,9 +57,7 @@ macro_rules! custom_keyword {
}
// TODO following functions are copied from sr-api-macros : do a merge to get a unique procedural
// macro tooling crate (this crate path does not look good for it)
// FIXME #1569, remove the following functions, which are copied from sr-api-macros
use proc_macro2::{TokenStream, Span};
use syn::Ident;
+1 -1
View File
@@ -485,7 +485,7 @@ macro_rules! decl_module {
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
// TODO: switching based on std feature is because of an issue in
// FIXME: switching based on std feature is because of an issue in
// serde-derive for when we attempt to derive `Deserialize` on these types,
// in a situation where we've imported `srml_support` as another name.
#[cfg(feature = "std")]
@@ -194,7 +194,7 @@ pub trait StorageMap<K: codec::Codec, V: codec::Codec> {
fn mutate<R, F: FnOnce(&mut Self::Query) -> R, S: Storage>(key: &K, f: F, storage: &S) -> R;
}
// TODO: Remove this in favour of `decl_storage` macro.
// FIXME #1466 Remove this in favour of `decl_storage` macro.
/// Declares strongly-typed wrappers around codec-compatible types in storage.
#[macro_export]
macro_rules! storage_items {
@@ -445,7 +445,6 @@ macro_rules! __storage_items_internal {
}
/// Get the key used to put the length field.
// TODO: concat macro should accept byte literals.
fn len_key() -> $crate::rstd::vec::Vec<u8> {
let mut key = $prefix.to_vec();
key.extend(b"len");
@@ -513,7 +512,7 @@ macro_rules! __handle_wrap_internal {
};
}
// TODO: revisit this idiom once we get `type`s in `impl`s.
// FIXME: revisit this idiom once we get `type`s in `impl`s.
/*impl<T: Trait> Module<T> {
type Now = super::Now<T>;
}*/
@@ -24,8 +24,6 @@ use codec::{Codec, Decode, KeyedVec, Input};
#[macro_use]
pub mod generator;
// TODO: consider using blake256 to avoid possible preimage attack.
struct IncrementalInput<'a> {
key: &'a [u8],
pos: usize,
+2 -2
View File
@@ -344,9 +344,9 @@ impl<T: Trait> Module<T> {
#[cfg(any(feature = "std", test))]
pub fn externalities() -> TestExternalities<Blake2Hasher> {
TestExternalities::new(map![
twox_128(&<BlockHash<T>>::key_for(T::BlockNumber::zero())).to_vec() => [69u8; 32].encode(), // TODO: replace with Hash::default().encode
twox_128(&<BlockHash<T>>::key_for(T::BlockNumber::zero())).to_vec() => [69u8; 32].encode(),
twox_128(<Number<T>>::key()).to_vec() => T::BlockNumber::one().encode(),
twox_128(<ParentHash<T>>::key()).to_vec() => [69u8; 32].encode(), // TODO: replace with Hash::default().encode
twox_128(<ParentHash<T>>::key()).to_vec() => [69u8; 32].encode(),
twox_128(<RandomSeed<T>>::key()).to_vec() => T::Hash::default().encode()
])
}