Skip to content

Commit

Permalink
update comments
Browse files Browse the repository at this point in the history
  • Loading branch information
timwu20 committed Dec 12, 2024
1 parent e351dec commit a063b68
Show file tree
Hide file tree
Showing 17 changed files with 81 additions and 89 deletions.
4 changes: 1 addition & 3 deletions internal/client/db/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (BlocksPruningSome) isBlocksPruning() {}
type DatabaseSource struct {
// the handle to the custom storage
DB database.Database[hash.H256]
// if set, the `create` flag will be required to open such datasource
// if set, the create flag will be required to open such datasource
RequireCreateFlag bool
}

Expand Down Expand Up @@ -385,8 +385,6 @@ type Backend[
genesisState *dbGenesisStorage[H, Hasher] // can be nil to represent no genesisState
genesisStateMtx sync.RWMutex
sharedTrieCache *cache.SharedTrieCache[H] // can be nil to respresent no shared trie cache
// io_stats: FrozenForDuration<(kvdb::IoStats, StateUsageInfo)>,
// state_usage: Arc<StateUsageStats>,
}

// Create a new instance of database backend.
Expand Down
8 changes: 4 additions & 4 deletions internal/client/db/backend_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestBackend_Integration(t *testing.T) {
t.Run("tree_route_regression", func(t *testing.T) {
// NOTE: this is a test for a regression introduced in #3665, the result
// of tree_route would be erroneously computed, since it was taking into
// account the `ancestor` in `CachedHeaderMetadata` for the comparison.
// account the ancestor in CachedHeaderMetadata for the comparison.
// in this test we simulate the same behavior with the side-effect
// triggering the issue being eviction of a previously fetched record
// from the cache, therefore this test is dependent on the LRU cache
Expand All @@ -38,13 +38,13 @@ func TestBackend_Integration(t *testing.T) {
}
block7000 := parent

// This will cause the ancestor of `block100` to be set to `genesis` as a side-effect.
// This will cause the ancestor of block100 to be set to genesis as a side-effect.
_, err := p_blockchain.LowestCommonAncestor(blockchain, genesis, block100)
require.NoError(t, err)

// While traversing the tree we will have to do 6900 calls to
// `header_metadata`, which will make sure we will exhaust our cache
// which only takes 5000 elements. In particular, the `CachedHeaderMetadata` struct for
// HeaderMetadata, which will make sure we will exhaust our cache
// which only takes 5000 elements. In particular, the CachedHeaderMetadata struct for
// block #100 will be evicted and will get a new value (with ancestor set to its parent).
treeRoute, err := p_blockchain.NewTreeRoute(blockchain, block100, block7000)
require.NoError(t, err)
Expand Down
4 changes: 0 additions & 4 deletions internal/client/db/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,6 @@ var (
)

func openDatabase(dbSource DatabaseSource, create bool) (database.Database[hash.H256], error) {
// Maybe migrate (copy) the database to a type specific subdirectory to make it
// possible that light and full databases coexist
// NOTE: This function can be removed in a few releases
// maybe_migrate_to_type_subdir::<Block>(db_source, db_type)?;
if dbSource.RequireCreateFlag && !create {
return nil, errDoesNotExist
}
Expand Down
2 changes: 1 addition & 1 deletion internal/client/state-db/statedb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ func TestStateDB_BlockRecordUnavailable(t *testing.T) {
assert.Equal(t, IsPrunedPruned, stateDB.IsPruned(hash.NewH256FromLowUint64BigEndian(3), 3))

// canonicalize block 5 but not commit it to db, block 4 is not pruned due to it is not
// commit to db yet (unavailable), return `MaybePruned` here because `apply_pending` is not
// commit to db yet (unavailable), return MaybePruned here because apply_pending is not
// called and block 3 is still in cache
c2, err := stateDB.CanonicalizeBlock(hash.NewH256FromLowUint64BigEndian(5))
assert.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion internal/kvdb/kvdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ type KeyValueDB interface {
// For a given start prefix (inclusive), returns the correct end prefix (non-inclusive).
// This assumes the key bytes are ordered in lexicographical order.
// Since key length is not limited, for some case we return nil because there is
// no bounded limit (every keys in the series `[]`, `[255]`, `[255, 255]` ...).
// no bounded limit (every keys in the series [], [255], [255, 255] ...).
func EndPrefix(prefix []byte) []byte {
for len(prefix) > 0 && prefix[len(prefix)-1] == 0xff {
prefix = prefix[:len(prefix)-1]
Expand Down
1 change: 0 additions & 1 deletion internal/kvdb/memory-kvdb/memory_kvdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (

var _ kvdb.KeyValueDB = &MemoryKVDB{}

// The number of columns required to run `test_delete_prefix`.
const DeletePrefixNumColumns uint32 = 7

func Test_MemoryKVDB(t *testing.T) {
Expand Down
20 changes: 10 additions & 10 deletions internal/primitives/blockchain/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

// Header is the blockchain database header backend. Does not perform any validation.
type HeaderBackend[Hash runtime.Hash, N runtime.Number, Header runtime.Header[N, Hash]] interface {
// Get block header. Returns `nil` if block is not found.
// Get block header. Returns nil if block is not found.
Header(hash Hash) (*Header, error)

// Get blockchain info.
Expand All @@ -21,10 +21,10 @@ type HeaderBackend[Hash runtime.Hash, N runtime.Number, Header runtime.Header[N,
// Get block status.
Status(hash Hash) (BlockStatus, error)

// Get block number by hash. Returns `nil` if the header is not in the chain.
// Get block number by hash. Returns nil if the header is not in the chain.
Number(hash Hash) (*N, error)

// Get block hash by number. Returns `nil` if the header is not in the chain.
// Get block hash by number. Returns nil if the header is not in the chain.
Hash(number N) (*Hash, error)

// Convert an arbitrary block ID into a block hash.
Expand All @@ -39,9 +39,9 @@ type Backend[Hash runtime.Hash, N runtime.Number, Header runtime.Header[N, Hash]
HeaderBackend[Hash, N, Header]
HeaderMetadata[Hash, N]

// Get block body. Returns `nil` if block is not found.
// Get block body. Returns nil if block is not found.
Body(hash Hash) ([]runtime.Extrinsic, error)
// Get block justifications. Returns `nil` if no justification exists.
// Get block justifications. Returns nil if no justification exists.
Justifications(hash Hash) (runtime.Justifications, error)
// Get last finalized block hash.
LastFinalized() (Hash, error)
Expand All @@ -53,23 +53,23 @@ type Backend[Hash runtime.Hash, N runtime.Number, Header runtime.Header[N, Hash]

// Returns displaced leaves after the given block would be finalized.
//
// The returned leaves do not contain the leaves from the same height as `blockNumber`.
// The returned leaves do not contain the leaves from the same height as blockNumber.
DisplacedLeavesAfterFinalizing(blockNumber N) ([]Hash, error)

// Return hashes of all blocks that are children of the block with `parentHash`.
// Return hashes of all blocks that are children of the block with parentHash.
Children(parentHash Hash) ([]Hash, error)

// Get the most recent block hash of the longest chain that contains
// a block with the given `baseHash`.
// a block with the given baseHash.
//
// The search space is always limited to blocks which are in the finalized
// chain or descendents of it.
//
// Returns `nil` if `basehash` is not found in search space.
// Returns nil if basehash is not found in search space.
LongestContaining(baseHash Hash, importLock *sync.RWMutex) (*Hash, error)

// Get single indexed transaction by content hash. Note that this will only fetch transactions
// that are indexed by the runtime with `storage_index_transaction`.
// that are indexed by the runtime with storage_index_transaction.
IndexedTransaction(hash Hash) ([]byte, error)

// Check if indexed transaction exists.
Expand Down
8 changes: 4 additions & 4 deletions internal/primitives/blockchain/header_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ type HashNumber[H runtime.Hash, N runtime.Number] struct {
// The ancestry sets will include the given blocks, and thus the tree-route is
// never empty.
//
// ```text
//
// Tree route from R1 to E2. Retracted is [R1, R2, R3], Common is C, enacted [E1, E2]
//
// <- R3 <- R2 <- R1
Expand All @@ -182,12 +182,12 @@ type HashNumber[H runtime.Hash, N runtime.Number] struct {
//
// \-> E1 -> E2
//
// ```
//
//
// ```text
//
// Tree route from C to E2. Retracted empty. Common is C, enacted [E1, E2]
// C -> E1 -> E2
// ```
//
type TreeRoute[H runtime.Hash, N runtime.Number] struct {
// route: Vec<HashAndNumber<Block>>,
Route []HashNumber[H, N]
Expand Down
28 changes: 14 additions & 14 deletions internal/primitives/core/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const DevPhrase = "bottom drive obey lake curtain smoke basket hold race lonely

// DeriveJunction is a since derivation junction description. It is the single parameter
// used when creating a new secret key from an existing secret key and, in the case of
// `SoftRaw` and `SoftIndex` a new public key from an existing public key.
// SoftRaw and SoftIndex a new public key from an existing public key.
type DeriveJunction struct {
inner any
}
Expand Down Expand Up @@ -113,7 +113,7 @@ var junctionRegex = regexp.MustCompile(`/(/?[^/]+)`)

// Trait used for types that are really just a fixed-length array.
type Bytes interface {
// Return a `Vec<u8>` filled with raw data.
// Return a []byte filled with raw data.
Bytes() []byte
}

Expand All @@ -125,29 +125,29 @@ type Public[Signature any] interface {
Verify(sig Signature, message []byte) bool
}

// SecretURI A secret uri (`SURI`) that can be used to generate a key pair.
// SecretURI A secret uri (SURI) that can be used to generate a key pair.
//
// The `SURI` can be parsed from a string. The string is interpreted in the following way:
// The SURI can be parsed from a string. The string is interpreted in the following way:
//
// - If `string` is a possibly `0x` prefixed 64-digit hex string, then it will be interpreted
// directly as a secret key (aka "seed" in `subkey`).
// - If `string` is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
// - If string is a possibly 0x prefixed 64-digit hex string, then it will be interpreted
// directly as a secret key (aka "seed" in subkey).
// - If string is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
// be derived from it. In this case:
// - the phrase may be followed by one or more items delimited by `/` characters.
// - the path may be followed by `///`, in which case everything after the `///` is treated
// - the phrase may be followed by one or more items delimited by "/" characters.
// - the path may be followed by "///", in which case everything after the "///" is treated
//
// as a password.
// - If `string` begins with a `/` character it is prefixed with the public `DevPhrase`
// - If string begins with a "/" character it is prefixed with the public DevPhrase
// and interpreted as above.
//
// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as
// integers, non-numeric items as strings. Junctions prefixed with `/` are interpreted as soft
// junctions, and with `//` as hard junctions.
// integers, non-numeric items as strings. Junctions prefixed with "/"" are interpreted as soft
// junctions, and with "//" as hard junctions.
//
// There is no correspondence mapping between `SURI` strings and the keys they represent.
// There is no correspondence mapping between SURI strings and the keys they represent.
// Two different non-identical strings can actually lead to the same secret being derived.
// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros.
// Similarly an empty password (ending the `SURI` with `///`) is perfectly valid and will
// Similarly an empty password (ending the SURI with "///") is perfectly valid and will
// generally be equivalent to no password at all.
type SecretURI struct {
// The phrase to derive the private key.
Expand Down
45 changes: 22 additions & 23 deletions internal/primitives/core/ed25519/ed25519.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (p Public) Verify(sig Signature, message []byte) bool {
return ed25519.Verify(p[:], message, sig[:])
}

// NewPublic creates a new instance from the given 32-byte `data`.
// NewPublic creates a new instance from the given 32-byte data.
//
// NOTE: No checking goes on to ensure this is a real public key. Only use it if
// you are certain that the array actually is a pubkey.
Expand Down Expand Up @@ -112,7 +112,7 @@ func (p Pair) Sign(message []byte) Signature {
// NewGeneratedPair will generate new secure (random) key pair.
//
// This is only for ephemeral keys really, since you won't have access to the secret key
// for storage. If you want a persistent key pair, use `generate_with_phrase` instead.
// for storage. If you want a persistent key pair, use [NewGeneratedPairWithPhrase] instead.
func NewGeneratedPair() (Pair, [32]byte) {
seedSlice := make([]byte, 32)
_, err := rand.Read(seedSlice)
Expand All @@ -127,9 +127,9 @@ func NewGeneratedPair() (Pair, [32]byte) {

// NewGeneratedPairWithPhrase will generate new secure (random) key pair and provide the recovery phrase.
//
// You can recover the same key later with `from_phrase`.
// You can recover the same key later with NewPairFromPhrase.
//
// This is generally slower than `generate()`, so prefer that unless you need to persist
// This is generally slower than generate(), so prefer that unless you need to persist
// the key from the current session.
func NewGeneratedPairWithPhrase(password *string) (Pair, string, [32]byte) {
entropy, err := bip39.NewEntropy(128)
Expand All @@ -147,7 +147,7 @@ func NewGeneratedPairWithPhrase(password *string) (Pair, string, [32]byte) {
return pair, phrase, seed
}

// NewPairFromPhrase returns the KeyPair from the English BIP39 seed `phrase`, or `None` if it's invalid.
// NewPairFromPhrase returns the KeyPair from the English BIP39 seed phrase.
func NewPairFromPhrase(phrase string, password *string) (pair Pair, seed [32]byte, err error) {
pass := ""
if password != nil {
Expand All @@ -167,18 +167,17 @@ func NewPairFromPhrase(phrase string, password *string) (pair Pair, seed [32]byt
return NewPairFromSeedSlice(seedSlice), seed, nil
}

// NewPairFromSeed will generate new key pair from the provided `seed`.
// NewPairFromSeed will generate new key pair from the provided seed.
//
// @WARNING: THIS WILL ONLY BE SECURE IF THE `seed` IS SECURE. If it can be guessed
// @WARNING: THIS WILL ONLY BE SECURE IF THE seed IS SECURE. If it can be guessed
// by an attacker then they can also derive your key.
func NewPairFromSeed(seed [32]byte) Pair {
return NewPairFromSeedSlice(seed[:])
}

// NewPairFromSeedSlice will make a new key pair from secret seed material. The slice must be the correct size or
// it will return `None`.
// NewPairFromSeedSlice will make a new key pair from secret seed material.
//
// @WARNING: THIS WILL ONLY BE SECURE IF THE `seed` IS SECURE. If it can be guessed
// @WARNING: THIS WILL ONLY BE SECURE IF THE seed IS SECURE. If it can be guessed
// by an attacker then they can also derive your key.
func NewPairFromSeedSlice(seedSlice []byte) Pair {
secret := ed25519.NewKeyFromSeed(seedSlice)
Expand All @@ -189,37 +188,37 @@ func NewPairFromSeedSlice(seedSlice []byte) Pair {
}
}

// NewPairFromStringWithSeed interprets the string `s` in order to generate a key Pair. Returns
// NewPairFromStringWithSeed interprets the string s in order to generate a key Pair. Returns
// both the pair and an optional seed, in the case that the pair can be expressed as a direct
// derivation from a seed (some cases, such as Sr25519 derivations with path components, cannot).
//
// This takes a helper function to do the key generation from a phrase, password and
// junction iterator.
//
// - If `s` is a possibly `0x` prefixed 64-digit hex string, then it will be interpreted
// directly as a secret key (aka "seed" in `subkey`).
// - If `s` is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
// - If s is a possibly "0x" prefixed 64-digit hex string, then it will be interpreted
// directly as a secret key (aka "seed" in subkey).
// - If s is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
// be derived from it. In this case:
// - the phrase may be followed by one or more items delimited by `/` characters.
// - the path may be followed by `///`, in which case everything after the `///` is treated
// - the phrase may be followed by one or more items delimited by "/" characters.
// - the path may be followed by "///", in which case everything after the "///" is treated
//
// as a password.
// - If `s` begins with a `/` character it is prefixed with the Substrate public `DevPhrase`
// - If s begins with a "/" character it is prefixed with the Substrate public DevPhrase
// and
//
// interpreted as above.
//
// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as
// integers, non-numeric items as strings. Junctions prefixed with `/` are interpreted as soft
// junctions, and with `//` as hard junctions.
// integers, non-numeric items as strings. Junctions prefixed with "/" are interpreted as soft
// junctions, and with "//" as hard junctions.
//
// There is no correspondence mapping between SURI strings and the keys they represent.
// Two different non-identical strings can actually lead to the same secret being derived.
// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros.
// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will
// Similarly an empty password (ending the SURI with "///") is perfectly valid and will
// generally be equivalent to no password at all.
//
// `nil` is returned if no matches are found.
// nil is returned if no matches are found.
func NewPairFromStringWithSeed(s string, passwordOverride *string) (
pair crypto.Pair[[32]byte, Signature], seed [32]byte, err error,
) {
Expand Down Expand Up @@ -255,7 +254,7 @@ func NewPairFromStringWithSeed(s string, passwordOverride *string) (
return root.Derive(sURI.Junctions, &seed)
}

// NewPairFromString interprets the string `s` in order to generate a key pair.
// NewPairFromString interprets the string s in order to generate a key pair.
func NewPairFromString(s string, passwordOverride *string) (crypto.Pair[[32]byte, Signature], error) {
pair, _, err := NewPairFromStringWithSeed(s, passwordOverride)
return pair, err
Expand All @@ -266,7 +265,7 @@ var _ crypto.Pair[[32]byte, Signature] = Pair{}
// Signature is a signature (a 512-bit value).
type Signature [64]byte

// NewSignatureFromRaw constructors a new instance from the given 64-byte `data`.
// NewSignatureFromRaw constructors a new instance from the given 64-byte data.
//
// NOTE: No checking goes on to ensure this is a real signature. Only use it if
// you are certain that the array actually is a signature.
Expand Down
Loading

0 comments on commit a063b68

Please sign in to comment.