core

package
v0.0.0-...-e0ea175 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KeySize       = 32 // Standard key size for Verkle trees
	LeafValueSize = 32 // Define LeafValueSize if it's standard for leaf values in Verkle trees
)

Variables

This section is empty.

Functions

func CalculateGas

func CalculateGas(dataSize int) int

CalculateGas computes the gas fee based on the size of the transaction data.

func ConvertJSONToProto

func ConvertJSONToProto(jsonTx thrylos.TransactionJSON) *thrylos.Transaction

func ConvertProtoInputs

func ConvertProtoInputs(inputs []*thrylos.UTXO) []shared.UTXO

func ConvertProtoOutputs

func ConvertProtoOutputs(outputs []*thrylos.UTXO) []shared.UTXO

func ConvertProtoTransactionToShared

func ConvertProtoTransactionToShared(protoTx *thrylos.Transaction) shared.Transaction

func ConvertProtoUTXOToShared

func ConvertProtoUTXOToShared(protoUTXO *thrylos.UTXO) shared.UTXO

ConvertProtoUTXOToShared converts a Protobuf-generated UTXO to your shared UTXO type.

func ConvertSharedTransactionToProto

func ConvertSharedTransactionToProto(tx *shared.Transaction) *thrylos.Transaction

func ConvertThrylosToProtoTransaction

func ConvertThrylosToProtoTransaction(thrylosTx *thrylos.Transaction) *thrylos.Transaction

Assuming ConvertThrylosToSharedTransaction is a function you will create to convert between these transaction types ConvertThrylosToProtoTransaction converts your internal transaction representation to the protobuf representation

func NewVerkleTree

func NewVerkleTree(data [][]byte) (verkle.VerkleNode, error)

func SecureRandomInt

func SecureRandomInt(max int) (int, error)

func ThrylosToShared

func ThrylosToShared(tx *thrylos.Transaction) *shared.Transaction

Types

type Block

type Block struct {
	// Index is the position of the block in the blockchain, starting from 0 for the genesis block.
	Index int32 `json:"index"`

	// Timestamp represents the time at which the block was created, measured in seconds since
	// the Unix epoch. It ensures the chronological order of blocks within the blockchain.
	Timestamp int64 `json:"timestamp"`

	// VerkleRoot is the root hash of the Verkle tree constructed from the block's transactions.
	// It provides a succinct proof of the transactions' inclusion in the block.
	VerkleRoot []byte `json:"verkleRootBase64,omitempty"` // Optionally encoded in base64 if to be readable

	// PrevHash stores the hash of the previous block in the chain, establishing the link between
	// this block and its predecessor. This linkage is crucial for the blockchain's integrity.
	PrevHash string `json:"prevHash"`

	// Hash is the block's own hash, computed from its contents and metadata. It uniquely identifies
	// the block and secures the blockchain against tampering.
	Hash string `json:"Hash"` // Ensure the hash is part of the block's structure

	// Transactions is the list of transactions included in the block. Transactions are the actions
	// that modify the blockchain's state, such as transferring assets between parties.
	Transactions []*thrylos.Transaction `json:"transactions"`

	// Validator is the identifier for the node or party that created and validated the block.
	// In proof-of-stake systems, this would be the stakeholder who was entitled to produce the block.
	Validator string `json:"validator"`

	Error error // Added to capture errors during block processing

	Data string `json:"data"` // Assuming the block's content is just a string for simplicity
	// contains filtered or unexported fields
}

func NewBlock

func NewBlock(index int, transactions []shared.Transaction, prevHash string, validator string, prevTimestamp int64, privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey) *Block

NewBlock creates a new block with the specified parameters, including the index, transactions, previous hash, and validator. This function also calculates the current timestamp and the block's hash, ensuring the block is ready to be added to the blockchain.

func NewGenesisBlock

func NewGenesisBlock() *Block

NewGenesisBlock creates and returns the genesis block for the blockchain. The genesis block is the first block in the blockchain, serving as the foundation upon which the entire chain is built.

func (*Block) ComputeHash

func (b *Block) ComputeHash() string

func (*Block) GetVerkleRootBase64

func (b *Block) GetVerkleRootBase64() string

Encoding binary data as base64 in JSON is common as not supported

func (*Block) GobDecode

func (b *Block) GobDecode(data []byte) error

GobDecode overrides the default Gob decoding for Block

func (*Block) GobEncode

func (b *Block) GobEncode() ([]byte, error)

GobEncode overrides the default Gob encoding for Block

func (*Block) InitializeVerkleTree

func (b *Block) InitializeVerkleTree() error

InitializeVerkleTree initializes the Verkle Tree lazily and calculates its root.

type Blockchain

type Blockchain struct {
	// Blocks holds the sequence of blocks that constitute the blockchain. Each block contains
	// a set of transactions and is linked to the previous block, forming the chain.
	Blocks []*Block

	// Genesis points to the first block in the blockchain, known as the Genesis block. This block
	// is the foundation of the blockchain, with no preceding block.
	Genesis *Block

	// Adding transactions to the pending transactions pool
	PendingTransactions []*thrylos.Transaction

	// Stakeholders maps validator addresses to their respective stakes in the network. This is
	// used in proof-of-stake (PoS) consensus mechanisms to determine validators' rights to create
	// new blocks based on the size of their stake
	Stakeholders map[string]int

	// UTXOs tracks unspent transaction outputs, which represent the current state of ownership
	// of the blockchain's assets. It is a key component in preventing double spending.
	UTXOs map[string][]*thrylos.UTXO

	// Forks captures any divergences in the blockchain, where two or more blocks are found to
	// have the same predecessor. Forks are resolved through mechanisms that ensure consensus
	// on a single chain.
	Forks []*Fork

	// Mu provides concurrency control to ensure that operations on the blockchain are thread-safe,
	// preventing race conditions and ensuring data integrity.
	Mu sync.RWMutex

	// Database provides an abstraction over the underlying database technology used to persist
	// blockchain data, facilitating operations like adding blocks and retrieving blockchain state
	Database shared.BlockchainDBInterface // Updated the type to interface

	PublicKeyMap map[string]ed25519.PublicKey // To store public keys
	// contains filtered or unexported fields
}

Blockchain represents the entire blockchain structure, encapsulating all blocks, stakeholders, and transactions within the network. It serves as the central ledger of the system, tracking the state of the blockchain, including ownership of assets through UTXOs (Unspent Transaction Outputs), and the resolution of forks, ensuring the integrity and continuity of the chain.

func NewBlockchain

func NewBlockchain(dataDir string, aesKey []byte) (*Blockchain, error)

NewBlockchain initializes and returns a new instance of a Blockchain. It sets up the necessary infrastructure, including the genesis block and the database connection for persisting the blockchain state.

func (*Blockchain) AddBlock

func (bc *Blockchain) AddBlock(transactions []*thrylos.Transaction, validator string, prevHash string, optionalTimestamp ...int64) (bool, error)

AddBlock adds a new block to the blockchain, with an optional timestamp. If the timestamp is 0, the current system time is used as the block's timestamp.

func (*Blockchain) AddPendingTransaction

func (bc *Blockchain) AddPendingTransaction(tx *thrylos.Transaction)

AddPendingTransaction adds a new transaction to the pool of pending transactions.

func (*Blockchain) CheckChainIntegrity

func (bc *Blockchain) CheckChainIntegrity() bool

CheckChainIntegrity verifies the entire blockchain for hash integrity and chronological order, ensuring that no blocks have been altered or inserted maliciously. It's a safeguard against tampering and a key component in the blockchain's security mechanisms.

func (*Blockchain) CreateBlock

func (bc *Blockchain) CreateBlock(transactions []*thrylos.Transaction, validator string, prevHash string, timestamp int64) *Block

CreateBlock generates a new block with the given transactions, validator, previous hash, and timestamp. This method encapsulates the logic for building a block to be added to the blockchain.

func (*Blockchain) DelegateStake

func (bc *Blockchain) DelegateStake(from, to string, amount int) error

This method will adjust the stake between two addresses, which represents delegating stake from one user (the delegator) to another (the delegatee or validator).

func (*Blockchain) GetBalance

func (bc *Blockchain) GetBalance(address string) (int, error)

func (*Blockchain) GetBlock

func (bc *Blockchain) GetBlock(blockNumber int) (*Block, error)

func (*Blockchain) GetBlockByID

func (bc *Blockchain) GetBlockByID(id string) (*Block, error)

func (*Blockchain) GetBlockCount

func (bc *Blockchain) GetBlockCount() int

func (*Blockchain) GetChainID

func (bc *Blockchain) GetChainID() string

func (*Blockchain) GetLastBlock

func (bc *Blockchain) GetLastBlock() (*Block, int, error)

func (*Blockchain) GetTransactionByID

func (bc *Blockchain) GetTransactionByID(id string) (*thrylos.Transaction, error)

func (*Blockchain) GetTransactionCount

func (bc *Blockchain) GetTransactionCount(address string) int

func (*Blockchain) GetUTXOsForAddress

func (bc *Blockchain) GetUTXOsForAddress(address string) []shared.UTXO

GetUTXOsForAddress returns all UTXOs for a given address.

func (*Blockchain) InsertOrUpdatePublicKey

func (bc *Blockchain) InsertOrUpdatePublicKey(address string, publicKey []byte, keyType string) error

In Blockchain

func (*Blockchain) ProcessPendingTransactions

func (bc *Blockchain) ProcessPendingTransactions(validator string) (*Block, error)

ProcessPendingTransactions processes all pending transactions, attempting to form a new block. ProcessPendingTransactions processes all pending transactions, attempting to form a new block.

func (*Blockchain) RegisterPublicKey

func (bc *Blockchain) RegisterPublicKey(pubKey string) error

func (*Blockchain) RegisterValidator

func (bc *Blockchain) RegisterValidator(address string, pubKey string) error

RegisterValidator registers or updates a validator's information in the blockchain.

func (*Blockchain) ResolveForks

func (bc *Blockchain) ResolveForks()

func (*Blockchain) RetrievePublicKey

func (bc *Blockchain) RetrievePublicKey(ownerAddress string) (ed25519.PublicKey, error)

In blockchain.go, within your Blockchain struct definition

func (*Blockchain) RewardValidator

func (bc *Blockchain) RewardValidator(validator string, reward int)

RewardValidator rewards the validator with new tokens

func (*Blockchain) SelectValidator

func (bc *Blockchain) SelectValidator() string

func (*Blockchain) SlashMaliciousValidator

func (bc *Blockchain) SlashMaliciousValidator(validatorAddress string, slashAmount int)

func (*Blockchain) Status

func (bc *Blockchain) Status() string

func (*Blockchain) TotalStake

func (bc *Blockchain) TotalStake() int

TotalStake calculates the total amount of stake from all stakeholders in the blockchain. This is used in consensus mechanisms that involve staking.

func (*Blockchain) UpdateStake

func (bc *Blockchain) UpdateStake(address string, amount int) error

If the stake adjustment leads to a non-positive value, the stakeholder is removed from the map.

func (*Blockchain) ValidateBlock

func (bc *Blockchain) ValidateBlock(newBlock *Block, prevBlock *Block) bool

ValidateBlock checks if the block is valid

func (*Blockchain) VerifyPoSRules

func (bc *Blockchain) VerifyPoSRules(block Block) bool

VerifyPoSRules verifies the PoS rules for the given block

func (*Blockchain) VerifyTransaction

func (bc *Blockchain) VerifyTransaction(tx *thrylos.Transaction) (bool, error)

VerifyTransaction checks the validity of a transaction against the current state of the blockchain, including signature verification and double spending checks. It's essential for maintaining the Example snippet for VerifyTransaction method adjustment

type BlockchainStats

type BlockchainStats struct {
	NumberOfBlocks       int `json:"number_of_blocks"`
	NumberOfTransactions int `json:"number_of_transactions"`
	TotalStake           int `json:"total_stake"`
	NumberOfPeers        int `json:"number_of_peers"`
}

type ConsistentHashRing

type ConsistentHashRing struct {
	*consistent.Consistent
}

func NewConsistentHashRing

func NewConsistentHashRing() *ConsistentHashRing

func (*ConsistentHashRing) AddNode

func (c *ConsistentHashRing) AddNode(node string)

func (*ConsistentHashRing) GetNode

func (c *ConsistentHashRing) GetNode(key string) string

func (*ConsistentHashRing) GetReplicas

func (c *ConsistentHashRing) GetReplicas(key string, count int) []string

func (*ConsistentHashRing) ProxyGetHash

func (c *ConsistentHashRing) ProxyGetHash(value string) uint32

type Fork

type Fork struct {
	Index  int
	Blocks []*Block
}

Fork structure representing a fork in the blockchain

type Node

type Node struct {
	Address             string      // Network address of the node.
	Peers               []string    // Addresses of peer nodes for communication within the network.
	Blockchain          *Blockchain // The blockchain maintained by this node.
	Votes               []Vote      // Collection of votes for blocks from validators.
	Shard               *Shard      // Reference to the shard this node is part of, if sharding is implemented.
	PendingTransactions []*thrylos.Transaction
	PublicKeyMap        map[string]ed25519.PublicKey // Updated to store ed25519 public keys

	ResponsibleUTXOs map[string]shared.UTXO // Tracks UTXOs for which the node is responsible
	// contains filtered or unexported fields
}

Node defines a blockchain node with its properties and capabilities within the network. It represents both a ledger keeper and a participant in the blockchain's consensus mechanism. Each node maintains a copy of the blockchain, a list of peers, a shard reference, and a pool of pending transactions to be included in future blocks.

func NewNode

func NewNode(address string, knownPeers []string, dataDir string, shard *Shard, isTest bool) *Node

NewNode initializes a new Node with the given address, known peers, and shard information. It creates a new blockchain instance for the node and optionally discovers peers if not running in a test environment.

func (*Node) AddPeer

func (node *Node) AddPeer(peerAddress string)

AddPeer adds a new peer to the node's list of peers if it is not already present. This function ensures that the node maintains an up-to-date list of peers with which it can communicate. Duplicate addresses are ignored to prevent redundancy.

func (*Node) AddPendingTransaction

func (node *Node) AddPendingTransaction(tx *thrylos.Transaction) error

func (*Node) AssignUTXO

func (n *Node) AssignUTXO(txID string, utxo shared.UTXO)

func (*Node) Broadcast

func (node *Node) Broadcast()

Broadcast serializes the node's blockchain and sends it to all known peers. This function supports the network's consistency by ensuring that all peers have the latest state of the blockchain.

func (*Node) BroadcastBlock

func (node *Node) BroadcastBlock(block *Block)

BroadcastBlock sends a block to all peers in the network. This is part of the block propagation mechanism, ensuring that all nodes are aware of new blocks added to the blockchain.

func (*Node) BroadcastTransaction

func (node *Node) BroadcastTransaction(tx *shared.Transaction)

BroadcastTransaction sends a transaction to all peers in the network. This is part of the transaction propagation mechanism, ensuring that all nodes are aware of new transactions.

func (*Node) CollectInputsForTransaction

func (node *Node) CollectInputsForTransaction(amount int, senderAddress string) (inputs []shared.UTXO, change int, err error)

func (*Node) ConsensusInfoHandler

func (node *Node) ConsensusInfoHandler() http.HandlerFunc

func (*Node) CountVotes

func (node *Node) CountVotes()

CountVotes tallies the votes for blocks from validators and updates the blockchain accordingly. It plays a crucial role in consensus mechanisms where blocks are accepted based on validator votes.

func (*Node) CreateAndBroadcastTransaction

func (node *Node) CreateAndBroadcastTransaction(recipientAddress string, from *string, amount int, data *[]byte, gas *int) error

CreateAndBroadcastTransaction creates a new transaction with the specified recipient and amount, signs it with the sender's Ed25519 private key, and broadcasts it to the network.

func (*Node) CreateWalletHandler

func (node *Node) CreateWalletHandler() http.HandlerFunc

func (*Node) DelegateStakeHandler

func (node *Node) DelegateStakeHandler() http.HandlerFunc

func (*Node) DiscoverPeers

func (node *Node) DiscoverPeers()

DiscoverPeers iterates over the node's current list of peers and requests their peer lists. This allows the node to discover new peers in the network dynamically. Discovered peers are added using the AddPeer method.

func (*Node) GetBalance

func (node *Node) GetBalance(address string) (int64, error)

func (*Node) GetBalanceHandler

func (node *Node) GetBalanceHandler() http.HandlerFunc

func (*Node) GetBlockCount

func (node *Node) GetBlockCount() int

Assuming this is part of the Node struct

func (*Node) GetBlockHandler

func (node *Node) GetBlockHandler() http.HandlerFunc

GetBlockHandler retrieves a specific block by ID.

func (*Node) GetBlockchainStats

func (node *Node) GetBlockchainStats() BlockchainStats

func (*Node) GetPendingTransactions

func (node *Node) GetPendingTransactions() []*thrylos.Transaction

func (*Node) GetTransactionHandler

func (node *Node) GetTransactionHandler() http.HandlerFunc

GetTransactionHandler retrieves a specific transaction by ID.

func (*Node) GetTransactionReceipt

func (node *Node) GetTransactionReceipt(txHash string) (map[string]interface{}, error)

func (*Node) HasBlock

func (n *Node) HasBlock(blockHash string) bool

HasBlock checks whether a block with the specified hash exists in the node's blockchain.

func (*Node) HasTransaction

func (node *Node) HasTransaction(txID string) bool

HasTransaction checks whether a transaction with the specified ID exists in the node's pool of pending transactions.

func (*Node) ListTransactionsForBlockHandler

func (node *Node) ListTransactionsForBlockHandler() http.HandlerFunc

fetch all transactions for a given block

func (*Node) NetworkHealthHandler

func (node *Node) NetworkHealthHandler() http.HandlerFunc

Report the health of the node and its connectivity with other peers

func (*Node) PendingTransactionsHandler

func (node *Node) PendingTransactionsHandler() http.HandlerFunc

func (*Node) RegisterPublicKeyHandler

func (node *Node) RegisterPublicKeyHandler() http.HandlerFunc

Allows users to register their public keys with Thrylos, enssential for transactions where public keys are needed

func (*Node) RegisterValidatorHandler

func (node *Node) RegisterValidatorHandler() http.HandlerFunc

func (*Node) RetrievePublicKey

func (node *Node) RetrievePublicKey(address string) (ed25519.PublicKey, error)

func (*Node) SetChainID

func (n *Node) SetChainID(chainID string)

Hold the chain ID and then proviude a method to set it

func (*Node) Start

func (node *Node) Start()

Start initializes the HTTP server for the node, setting up endpoints for blockchain, block, peers, votes, and transactions handling. It also starts background tasks for discovering peers and counting votes.

func (*Node) StorePublicKey

func (node *Node) StorePublicKey(address string, publicKey ed25519.PublicKey)

func (*Node) SubmitTransactionHandler

func (node *Node) SubmitTransactionHandler() http.HandlerFunc

func (*Node) SyncBlockchain

func (node *Node) SyncBlockchain()

SyncBlockchain synchronizes the node's blockchain with its peers. It fetches blocks from peer nodes to ensure the node has the most current and accurate version of the blockchain.

func (*Node) SyncWithPeer

func (node *Node) SyncWithPeer(peer string)

SyncWithPeer fetches the blockchain from a specified peer and updates the node's blockchain if the peer's blockchain is longer. This function is part of the node's mechanism for maintaining consensus on the blockchain state across the network.

func (*Node) UpdateStakeHandler

func (node *Node) UpdateStakeHandler() http.HandlerFunc

func (*Node) VerifyAndProcessTransaction

func (node *Node) VerifyAndProcessTransaction(tx *thrylos.Transaction) error

VerifyAndProcessTransaction verifies the transaction's signature using Ed25519 and processes it if valid. VerifyAndProcessTransaction verifies the transaction's signature using Ed25519 and processes it if valid.

func (*Node) VoteForBlock

func (node *Node) VoteForBlock(block *Block)

VoteForBlock allows a node to cast a vote for a specific block. It is part of the consensus mechanism, where validators with a stake in the blockchain vote to determine the validity of blocks.

type Shard

type Shard struct {
	ID       int                    // Unique identifier for the shard.
	Nodes    []*Node                // List of nodes that are part of the shard.
	UTXOs    map[string]shared.UTXO // Current state of unspent transaction outputs managed by this shard.
	Blocks   []*Block               // Blocks that have been confirmed and added to the shard's blockchain.
	MaxNodes int                    // Maximum number of nodes allowed to be part of the shard.
}

Shard represents a subset of the blockchain network, designed to scale the network by dividing the transaction and block processing workload among multiple shards. Each shard maintains its own sequence of blocks, set of transactions (UTXOs), and participating nodes.

func NewShard

func NewShard(id int, maxNodes int) *Shard

NewShard initializes a new Shard with a specified identifier and maximum node capacity. It sets up the initial empty structures for nodes, UTXOs, and blocks within the shard.

func (*Shard) AddNode

func (s *Shard) AddNode(node *Node)

AddNode adds a new node to the shard's list of participating nodes. This method registers a node as part of the shard, allowing it to participate in the shard's transaction and block processing activities. The method may include additional logic to integrate the node into the shard's operations.

func (*Shard) AssignNode

func (s *Shard) AssignNode(node *Node) error

AssignNode attempts to add a node to the shard, ensuring the node is not already a member and that the shard has not reached its maximum capacity. It returns an error if the shard is full or if the node is already part of the shard.

func (*Shard) InitializeOrUpdateShard

func (s *Shard) InitializeOrUpdateShard()

Initialize or update the shard, including UTXO redistribution Initialize or update the shard, including UTXO redistribution

func (*Shard) RedistributeData

func (s *Shard) RedistributeData()

RedistributeData redistributes UTXOs among nodes based on a consistent hashing mechanism

type Stakeholder

type Stakeholder struct {
	Address string
	Stake   int
}

NewTransaction creates a new transaction

type Vote

type Vote struct {
	BlockHash string // Hash of the block that is being voted for.
	Validator string // Address of the validator casting the vote.
	Stake     int    // Stake amount of the validator at the time of voting.
}

Vote represents a vote cast by a validator for a specific block. It includes the block hash being voted for, the validator's address, and the stake the validator had at the time of voting. This is used in consensus mechanisms that involve staking and voting for block validity.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL