Documentation ¶
Index ¶
- func DBAddBlockchain(bs BlockchainCore) error
- func DBKeyExists() bool
- func GetPublicKeyFromHex(publicKeyHex string) *ecdsa.PublicKey
- type Block
- type BlockchainCore
- func DBGetBlockchain() (*BlockchainCore, error)
- func FetchBlocks(address string) (*BlockchainCore, error)
- func NewBlockchain(genesisBlock Block, address string) *BlockchainCore
- func NewBlockchainSync(bc1 *BlockchainCore, address string) *BlockchainCore
- func SyncBlockchain(address string) (*BlockchainCore, error)
- func (bc *BlockchainCore) AddBlock(b *Block)
- func (bc *BlockchainCore) AddTransactionToTransactionPool(transaction *Transaction)
- func (bc *BlockchainCore) BroadcastPeerList()
- func (bc *BlockchainCore) BroadcastTransaction(txn *Transaction)
- func (bc *BlockchainCore) CalculateTotalCrypto(address string) uint64
- func (bc *BlockchainCore) CheckStatus(address string) bool
- func (bc *BlockchainCore) DialUpdatePeers()
- func (bc *BlockchainCore) GetAllNonRewardedTransactions() []Transaction
- func (bc BlockchainCore) PeersToJson() []byte
- func (bc *BlockchainCore) ProofOfWorkMining(minersAddress string)
- func (bc *BlockchainCore) RunConsensus()
- func (bc *BlockchainCore) SendPeersList(address string)
- func (bc *BlockchainCore) SendTransactionPeer(address string, txn *Transaction)
- func (bc BlockchainCore) ToJson() string
- func (bc *BlockchainCore) UpdateBlockchain(newChain []*Block)
- func (bc *BlockchainCore) UpdatePeers(peers map[string]bool)
- type Transaction
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DBAddBlockchain ¶
func DBAddBlockchain(bs BlockchainCore) error
DBAddBlockchain: saves the blockchain core state to the database It takes a BlockchainCore struct and stores it as JSON in LevelDB Returns an error if database operations fail
func DBKeyExists ¶
func DBKeyExists() bool
func GetPublicKeyFromHex ¶
GetPublicKeyFromHex converts a hex string representation of a public key to an ECDSA public key It strips the hex prefix, splits the remaining string into x and y coordinates, and creates a new public key using the P256 curve
Types ¶
type Block ¶
type Block struct { BlockNumber uint64 `json:"block_number"` PrevHash string `json:"prev_hash"` Timestamp int64 `json:"timestamp"` Nonce int64 `json:"nonce"` Transactions []*Transaction `json:"transactions"` }
func NewBlock ¶
NewBlock creates a new Block instance with the provided previous hash and nonce value, initializing its timestamp to the current time and an empty transaction list
func (*Block) AddTransactionToTheBlock ¶
func (b *Block) AddTransactionToTheBlock(txn *Transaction)
AddTransactionToTheBlock: adds a transaction to the block's transaction list and updates its status to either SUCCESS or FAILED based on its verification status.
type BlockchainCore ¶
type BlockchainCore struct { TransactionPool []*Transaction `json:"transaction_pool"` Blocks []*Block `json:"blocks"` Address string `json:"address"` Peers map[string]bool `json:"peers"` MiningLocked bool `json:"mining_locked"` }
func DBGetBlockchain ¶
func DBGetBlockchain() (*BlockchainCore, error)
DBGetBlockchain: retrieves the blockchain core state from the database It opens the LevelDB database, gets the blockchain data, and unmarshals it into a BlockchainCore struct Returns a pointer to the BlockchainCore struct and any error that occurs
func FetchBlocks ¶
func FetchBlocks(address string) (*BlockchainCore, error)
FetchBlocks: fetches the last N blocks (defined by FETCH_BLOCK_NUMBER constant) from a given address. Makes an HTTP GET request to the fetch-consensus-blocks endpoint, reads the response data, and unmarshals it into a BlockchainCore struct. Returns a pointer to the blockchain containing the fetched blocks and any errors encountered.
func NewBlockchain ¶
func NewBlockchain(genesisBlock Block, address string) *BlockchainCore
NewBlockchain: creates a new blockchain instance with a genesis block If blockchain data exists in the database (checked via DBKeyExists), retrieves and returns it Otherwise creates a new blockchain with the genesis block and persists it via DBAddBlockchain Returns a pointer to the BlockchainCore instance in either case
func NewBlockchainSync ¶
func NewBlockchainSync(bc1 *BlockchainCore, address string) *BlockchainCore
NewBlockchainSync: creates a copy of an existing blockchain with a new address Takes a pointer to an existing BlockchainCore and a new address string Returns a pointer to the new BlockchainCore instance with updated address
func SyncBlockchain ¶
func SyncBlockchain(address string) (*BlockchainCore, error)
SyncBlockchain: retrieves and synchronizes the blockchain from a given address. It makes an HTTP GET request to the provided address, reads the blockchain data, and unmarshals it into a BlockchainCore struct. Returns a pointer to the synchronized blockchain and any errors encountered.
func (*BlockchainCore) AddBlock ¶
func (bc *BlockchainCore) AddBlock(b *Block)
AddBlock adds a new block to the blockchain and removes its transactions from the transaction pool. It takes a pointer to a Block as input and updates both the blockchain's transaction pool and blocks array. Transactions in the new block are removed from the pool to prevent double-spending.
func (*BlockchainCore) AddTransactionToTransactionPool ¶
func (bc *BlockchainCore) AddTransactionToTransactionPool(transaction *Transaction)
AddTransactionToTransactionPool: processes a new transaction and adds it to the transaction pool. It verifies the transaction's signature and checks if the sender has sufficient balance by simulating the impact of pending transactions. The transaction's status is updated based on verification results and it is added to the pool. The blockchain state is then persisted to the database.
func (*BlockchainCore) BroadcastPeerList ¶
func (bc *BlockchainCore) BroadcastPeerList()
BroadcastPeerList: broadcasts the blockchain's peer list to all active peers in the network. Iterates through the peer list, sending the peer list to each active peer except itself. Includes a delay between broadcasts to prevent network congestion.
func (*BlockchainCore) BroadcastTransaction ¶
func (bc *BlockchainCore) BroadcastTransaction(txn *Transaction)
BroadcastTransaction: broadcasts a transaction to all active peers in the network. Iterates through the peer list, sending the transaction to each active peer except itself. Includes a delay between broadcasts to prevent network congestion.
func (*BlockchainCore) CalculateTotalCrypto ¶
func (bc *BlockchainCore) CalculateTotalCrypto(address string) uint64
CalculateTotalCrypto: calculates the total balance of cryptocurrency for a given address by examining all successful transactions in both the blockchain and transaction pool. It adds received amounts (To) and subtracts sent amounts (From) for the address.
func (*BlockchainCore) CheckStatus ¶
func (bc *BlockchainCore) CheckStatus(address string) bool
CheckStatus: checks if a blockchain server at the given address is available and running. Makes an HTTP GET request to the server's status endpoint and verifies the response matches the expected blockchain status value. Returns true if the server is running and accessible, false otherwise.
func (*BlockchainCore) DialUpdatePeers ¶
func (bc *BlockchainCore) DialUpdatePeers()
DialUpdatePeers: continuously checks and updates the status of peers in the blockchain network. Iterates through the peer list periodically, checking each peer's status via HTTP and updating the peers map accordingly. The blockchain's own address is always marked as active. After updating peers, broadcasts the new peer list to the network and sleeps for the configured ping interval before the next update cycle.
func (*BlockchainCore) GetAllNonRewardedTransactions ¶
func (bc *BlockchainCore) GetAllNonRewardedTransactions() []Transaction
GetAllTransactions: retrieves all transactions from both the transaction pool and blocks in reverse chronological order (newest first). It first collects transactions from the transaction pool, then adds transactions from blocks, excluding mining reward transactions (those from BLOCKCHAIN_ADDRESS). Returns a slice of all non-reward transactions.
func (BlockchainCore) PeersToJson ¶
func (bc BlockchainCore) PeersToJson() []byte
PeersToJson converts the BlockchainCore structure to JSON bytes Returns the byte array representation of the BlockchainCore
func (*BlockchainCore) ProofOfWorkMining ¶
func (bc *BlockchainCore) ProofOfWorkMining(minersAddress string)
ProofOfWorkMining continuously mines new blocks using proof of work consensus. It takes a miner's address as input and rewards successful mining with coins. The function runs indefinitely, creating new blocks that meet the mining difficulty requirement by incrementing a nonce value until a valid hash is found.
func (*BlockchainCore) RunConsensus ¶
func (bc *BlockchainCore) RunConsensus()
func (*BlockchainCore) SendPeersList ¶
func (bc *BlockchainCore) SendPeersList(address string)
SendPeersList: sends the blockchain's peer list to a specified address via HTTP POST. Converts the peer list to JSON and sends it to the /send-peers-list endpoint at the given address.
func (*BlockchainCore) SendTransactionPeer ¶
func (bc *BlockchainCore) SendTransactionPeer(address string, txn *Transaction)
SendTransactionPeer: sends a transaction to a specified peer address via HTTP POST. Takes the peer's address and a transaction pointer as input, converts the transaction to JSON, and sends it to the peer's /send-transaction endpoint.
func (BlockchainCore) ToJson ¶
func (bc BlockchainCore) ToJson() string
ToJson converts the BlockchainCore structure to a JSON string Returns the JSON string representation or an error message if marshal fails
func (*BlockchainCore) UpdateBlockchain ¶
func (bc *BlockchainCore) UpdateBlockchain(newChain []*Block)
UpdateBlockchain: updates the blockchain with a new chain of blocks. Takes a slice of new blocks, updates the blockchain's blocks array by appending the new chain at the correct position based on block numbers, and updates the transaction pool by removing any transactions that are now included in the blockchain. Thread-safe using mutex locks. After updating, saves the new blockchain state to the database
func (*BlockchainCore) UpdatePeers ¶
func (bc *BlockchainCore) UpdatePeers(peers map[string]bool)
UpdatePeers: updates the peers map in the blockchain with the provided peers map. Takes a map of peer addresses to boolean values. Uses mutex locking to ensure thread safety when updating the peers. After updating, saves the blockchain state to the database.
type Transaction ¶
type Transaction struct { From string `json:"from"` To string `json:"to"` Value uint64 `json:"value"` Data []byte `json:"data"` Status string `json:"status"` Timestamp uint64 `json:"timestamp"` TransactionHash string `json:"transaction_hash"` PublicKey string `json:"public_key,omitempty"` Signature []byte `json:"Signature"` }
func NewTransaction ¶
func NewTransaction(from string, to string, value uint64, data []byte) *Transaction
NewTransaction creates and returns a new Transaction object initialized with the provided parameters and default values for Status, PublicKey, and Signature fields
func (Transaction) Hash ¶
func (t Transaction) Hash() string
Hash generates a SHA-256 hash of the transaction data and returns it as a hex string with prefix. The transaction is first marshaled to JSON, then hashed, and finally encoded to a hex string.
func (Transaction) ToJson ¶
func (t Transaction) ToJson() string
ToJson converts a Transaction object to its JSON string representation
func (Transaction) VerifyTransaction ¶
func (t Transaction) VerifyTransaction() bool
VerifyTransaction checks if the transaction is valid by verifying: 1. The value is not zero 2. The value does not exceed maximum uint64 3. The sender and receiver addresses are not the same 4. The signature is valid Returns true if all checks pass, false otherwise
func (Transaction) VeryifySignature ¶
func (t Transaction) VeryifySignature() bool
VeryifySignature verifies the digital signature of a transaction using ECDSA It first checks if signature and public key exist, then verifies the signature against the transaction hash using the public key. Returns true if signature is valid, false otherwise