# Review code
- In many places of the code block number was replaced by hash block, where it was impossible to do that, block number obtained after finalization is used.
- Also use block height in non-finalizable DAG
- Removed support for superfluous data such as uncles, blocks that were used for POW
### Main structs
##### `core/genesis.go`
- Changed the genesis structure
```go
type Genesis struct {
Config *params.ChainConfig `json:"config"`
Nonce uint64 `json:"nonce"`
Timestamp uint64 `json:"timestamp"`
ExtraData []byte `json:"extraData"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"`
Mixhash common.Hash `json:"mixHash"`
Coinbase common.Address `json:"coinbase"`
Alloc GenesisAlloc `json:"alloc" gencodec:"required"`
GasUsed uint64 `json:"gasUsed"`
ParentHashes []common.Hash `json:"parentHashes"`
Epoch uint64 `json:"epoch"`
Slot uint64 `json:"slot"`
Height uint64 `json:"height"`
BaseFee *big.Int `json:"baseFeePerGas"`
}
```
- While loading the genesis, create and save the genesisDag, so that there is a vertex (Tips) from which the blocks will start to be created
```go
genesisDag := &types.BlockDAG{
Hash: block.Hash(),
Height: 0,
LastFinalizedHash: block.Hash(),
LastFinalizedHeight: 0,
DagChainHashes: common.HashArray{},
FinalityPoints: common.HashArray{},
}
```
##### `core/types/block.go`
Added
+ ParentHashes - now an array of parent blocks, not a single hash as in ETH
+ Epoch, Slot - fix consensus iteration at the moment of block creation
+ Height - block height, calculated at block creation, used for dag ordering, and after finalization serves to determine block color:
+ If `Height == Number` then the block is blue (i.e., it has a stored state, which is calculated based on the state of the preceding blue block + a sequence of red block states in the finalization order between blue blocks),
+ otherwise - red
+ Number - serial number of the block in the finalized chain. It is an auxiliary field, not used when hashing the block, and is not stored in the block itself. The value is calculated and assigned during block finalization
```go
type Header struct {
ParentHashes common.HashArray `json:"parentHashes" gencodec:"required"`
Epoch uint64 `json:"epoch" gencodec:"required"`
Slot uint64 `json:"slot" gencodec:"required"`
Height uint64 `json:"height" gencodec:"required"`
Coinbase common.Address `json:"miner" gencodec:"required"`
Root common.Hash `json:"stateRoot" gencodec:"required"`
TxHash common.Hash `json:"transactionsRoot" gencodec:"required"`
ReceiptHash common.Hash `json:"receiptsRoot" gencodec:"required"`
Bloom Bloom `json:"logsBloom" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed" gencodec:"required"`
Time uint64 `json:"timestamp" gencodec:"required"`
Extra []byte `json:"extraData" gencodec:"required"`
MixDigest common.Hash `json:"mixHash"`
Nonce BlockNonce `json:"nonce"`
// BaseFee was added by EIP-1559 and is ignored in legacy headers.
BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"`
Number *uint64 `json:"number" rlp:"optional"`
}
```
`
```go
type HeaderMap map[common.Hash]*Header
```
The structure of the block header array. In the same file, there are many methods that allow you to get graph/sort/types based on this structure
```go
type BlockMap map[common.Hash]*Block
```
Similar structure as above. Only works with blocks
`core/types/block_dag.go`
```go
type Tips map[common.Hash]*BlockDAG
type BlockDAG struct {
Hash common.Hash
Height uint64
LastFinalizedHash common.Hash
LastFinalizedHeight uint64
// ordered non-finalized ancestors hashes
DagChainHashes common.HashArray
// ordered points of future finalization
FinalityPoints common.HashArray
}
```
Tips are the vertices of the graph that are not referenced yet.
BlockDAG is a structure for storing a block in the database (basic information about tips)
```go
const (
BSS_NOT_LOADED BlockState = 0
BSS_LOADED BlockState = 1
BSS_FINALIZED BlockState = 2
)
type GraphDag struct {
Hash common.Hash
Height uint64
Number uint64
Graph []*GraphDag
State BlockState
chLen *uint64
}
```
GraphDag is a virtual structure that represents the Directional Acyclic Block Graph represented by BlockDAG. It is used for ordering dag-chain
The file contains many functions for working with these entities
##### `protocols/eth/handler.go`
```go
// NodeInfo represents a short summary of the `eth` sub-protocol metadata
// known about the host peer.
type NodeInfo struct {
Versions []uint `json:"versions"` // Protocol versions
Network uint64 `json:"network"` // gwat network ID
Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules
LastFinNr uint64 `json:"lastFinNr"` // Last Finalized Number of node
Dag *common.HashArray `json:"dag"` // all current dag hashes: nil - has not synchronized tips
}
```
added
- LastFinNr - last finalizing block
- Dag - array of block hashes that are included in the current DAG (after the finalizing block)
- Versions - versions of supported protocols
##### `miner/assignment.go`
```go
type Assignment struct {
Slot uint64
Epoch uint64
ActiveMiners []common.Address
}
```
The structure needed to store the current slot, epoch and active block creators
##### `params/config.go`
Contains settings `devnet`, `testnet` и `mainnet`*
\* *`testnet и mainnet - будут реализованы после определения параметров сетей`*
### Main
##### `core/blockchain.go` `blockchain_insert.go` `blockchain_reader.go`
In these files is the work of loading and operating the current state, saving data to the database.
- Last Block
- Balances on the last block
- Transactions and receipts
- etc.
All other modules are linked in this file
```go
type BlockChain struct {
...
DagMu sync.RWMutex // finalizing lock
lastFinalizedBlock atomic.Value // Current last finalized block of the blockchain
lastFinalizedFastBlock atomic.Value // Current last finalized block of the fast-sync chain (may be above the blockchain!)
insBlockCache []*types.Block // Cache for blocks to insert late
...
}
```
##### `core/headerchain.go`
```go
type HeaderChain struct {
...
tips atomic.Value
tipsMu sync.RWMutex
lastFinalisedHeader atomic.Value // Current head of the header chain (may be above the block chain!)
lastFinalisedHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
...
}
```
The file implements the functionality of the current state of the blockchain:
- Link to last finalized block
- Last state Tips
- Data caching
### DAG
##### `internal/ethapi/api.go`
- `func (api *PublicDagAPI) Sync(ctx context.Context, data *dag.ConsensusInfo) (*dag.ConsensusResult, error)`
consensus request handler (namespace __dag__ method __sync__)
##### `dag/dag.go`
- `func (d *Dag) HandleConsensus(data *ConsensusInfo) *ConsensusResult`
It implements the logic of consensus request processing.
The procedure includes the following steps:
- Checking incoming epoch/slot values (must be greater than the value of the last call)
- Executing block finalization procedure
- Collecting candidates for the next finalization
- Generating and sending a response
- Starting block creation procedure
##### `dag/finalizer/finalizer.go`
- `func (f *Finalizer) Finalize(chain NrHashMap) error`
Implementation of the block finalization procedure
- `func (f *Finalizer) GetFinalizingCandidates() (*NrHashMap, error)`
Gathering candidates for the next finals
##### `dag/creator/ctreator.go`
- `func (c *Creator) CreateBlock(assigned *Assignment) (*types.Block, error)`
Starting the block creation procedure
### Block Propagation
##### `eth/handler.go`
- `func (h *handler) BroadcastBlock(block *types.Block, propagate bool)`
Distributes a new (created or received) block on the network
- `func newHandler(config *handlerConfig) (*handler, error)`
The function `newHandler` in the function `blockFetcher` is passed as a parameter to the function `inserter` which is called after the new block has arrived and is fully loaded
The `inserter` function calls the function `InsertPropagatedBlocks` which is in the file `core/blockchain.go` there is work logic for the insertion of the block in the dag-chain and updating types
The `inserter` itself is called in `eth/fetcher/block_fetcher` method `func (f *BlockFetcher) importBlocks(peer string, block *types.Block)`
### Node Synchronization
There are two types:
- Full, includes two steps
- synchronization of the finalized part (implemented on the basis of ETH synchronization, and actively uses the block finalization number)
- Synchronization dag part for non-finalized blocks
- Synchronization of unknown blocks, used to load blocks from a remote node and add them to the dag part. Works if:
- when a new pir is connected, if the finalized part is the same, but the dag part contains unknown blocks
- when receiving a new block when propagating a block that has an unknown block as parent
##### `eth/protocols/eth/handshake.go`
- `func (p *Peer) Handshake(network uint64, lastFinNr uint64, dag *common.HashArray, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter) error`
When a pir is connected, the nodes exchange the current state
##### `eth/sync.go`
- `func (cs *chainSyncer) loop()`
When the pira is connected, it brings up the method `nextSyncOp`
- `func (cs *chainSyncer) nextSyncOp() *chainSyncOp`
Reconciles the states of the nodes and prepares the data for synchronization, the result is the synchronization process is started `doSync`
-`func (h *handler) doSync(op *chainSyncOp) error`
Starts the synchronization procedure, processes its result, and distributes the received blocks over the network
##### `eth/downloader/downloader.go`
- `func (d *Downloader) Synchronise(id string, dag common.HashArray, lastFinNr uint64, mode SyncMode, dagOnly bool) error`
Start the synchronization (the `synchronise` method, which runs `syncWithPeer`) and process the result
- `func (d *Downloader) spawnSync(fetchers []func() error) error`
Synchronization of the finalized part
- `func (d *Downloader) syncWithPeerDagChain(p *peerConnection) (err error)`
Synchronizing the dag part
- `func (d *Downloader) syncWithPeerUnknownDagBlocks(p *peerConnection, dag common.HashArray) (err error)`
Synchronization of unknown blocks, which are in the dag of a remote node, or in the ancestors of a block received from the network
##### `eth/downloader/peer.go`
Two functions were added
- `func (w *lightPeerWrapper) GetDagInfo() (uint64, *common.HashArray)`
Return information on the current Dag
- `func (w *lightPeerWrapper) RequestHeadersByHashes(h common.HashArray)`
Retrieve information about blocks by their hashes
##### `eth/protocols/eth/peer.go`
```go
type Peer struct {
...
lastFinNr uint64 // Latest advertised dag lastFinNr
dag *common.HashArray // Latest advertised dag hashes
...
}
```
Three functions have been added:
- `func (p *Peer) RequestDag(fromFinNr uint64) error`
Request a dag part starting from a certain finalized block
- `func (p *Peer) ReplyDagData(id uint64, dag common.HashArray) error`
Return the dag to the query
- `func (p *Peer) RequestHeadersByHashes(hashes common.HashArray) error`
Request hash blocks
##### `protocols/eth/protocol.go`
Expanded with 2 messages
- GetDag
- Dag
### les & light
Additional modes of node operation
##### `les/peer.go`
```go
type peerCommons struct {
...
id string // Peer identity.
headInfo blockInfo // Last announced finalized block information.
tipsInfo []blockInfo // Last announced tips information
...
}
```
contains the fields required for both the peer server and the peer client.
There are also functions that are needed for synchronization between nodes
- GetDagInfo
- requestHeadersByHashes
##### `les/server_requests.go`
##### `les/sync.go`
Changed the handlers needed to synchronize the nodes
##### `light/lightchain.go`
##### `light/txpool.go`
We have made changes in the synchronization of light clients. Basically, instead of the current head we use the head of the last finalized block
### Save to DB
##### `core/rawdb/accessors_chains.go`
At the very end, methods for saving and reading from the database of finalized blocks, dag blocks, types, children are implemented
### API
##### `internal/ethapi/api.go`
Instead of the current head we use the head of the last finalized block. in this way the api check shows the balance of the last finalized block
### Next step
1. Connect and fix the freezer
2. Check and correct operation in les & light modes
3. Deal with forks (keep last London)