Documentation
¶
Overview ¶
Package sdk is a software development kit for building blockchain applications. File sdk/address.go - Address for all Address related Protocol based transactions
This file defines the Address structure and associated methods for handling blockchain addresses within the SDK. It provides functionality for creating, manipulating, and hashing blockchain addresses.
The Address structure represents a blockchain address with two components: 1. RawAddress: The original, unmodified address string. 2. PrependedAddress: The address with the blockchain symbol prepended.
Key features and functionalities: - Creation of new Address instances with NewAddress function. - Retrieval of raw and prepended addresses. - Generation of address hashes using SHA-256.
The file implements the following main components: 1. Address struct: Represents a blockchain address. 2. NewAddress function: Creates a new Address instance. 3. GetRawAddress method: Returns the raw address string. 4. GetPrependedAddress method: Returns the address with the blockchain symbol prepended. 5. prependSymbol function: Helper function to prepend the blockchain symbol to an address. 6. GetAddressHash method: Calculates and returns the SHA-256 hash of the prepended address.
This implementation allows for flexible address handling within the blockchain SDK, supporting operations such as address creation, modification, and hashing. The use of prepended addresses with blockchain symbols enables easy identification and categorization of addresses across different blockchain networks.
Usage of this file's components is essential for proper address management throughout the blockchain application, ensuring consistency and security in address handling and representation
Package sdk is a software development kit for building blockchain applications. File sdk/api.go - API for the blockchain
Package sdk is a software development kit for building blockchain applications. File sdk/apiEndpointsAccount.go -
Package sdk is a software development kit for building blockchain applications. File sdk/apikey.go - API key middleware
Package sdk is a software development kit for building blockchain applications. File sdk/banktx.go - Bank Transaction for all Currency reelated Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File: sdk/block.go - Block in the blockchain
Package sdk is a software development kit for building blockchain applications. File sdk/blockchaininfo.go - Blockchain Info for all Blockchain related Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/coinbasetx.go - The Coinbase transaction
Package sdk is a software development kit for building blockchain applications. File sdk/common.go - Common functions for the sdk
Package sdk is a software development kit for building blockchain applications. File sdk/const.go - Constants for the blockchain
Package sdk is a software development kit for building blockchain applications. File sdk/flags.go - Flags for the blockchain
Package sdk is a software development kit for building blockchain applications. File sdk/html5.go - HTML5 related functions for the SDK
Package sdk is a software development kit for building blockchain applications. File sdk/localstorage.go - Local Storage for all data persist manager
Package sdk is a software development kit for building blockchain applications. File sdk/messagetx.go - Message Transaction for all Instant Messaging related Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/node.go - Node for all Node related Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/persisttx.go - Persistance Transaction for all On Chain Storage related Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/puid.go - Personal Unique Identifier for all User related Protocol based transactions
Package sdk is a software development kit for building blockchain applications.
Package sdk is a software development kit for building blockchain applications. File sdk/transaction.go - Base Transaction for all Dynamic Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/vault.go - Vault for all Vault related Protocol based transactions
Package sdk is a software development kit for building blockchain applications. File sdk/wallet.go - Wallet for all Wallet related Protocol based transactions
Index ¶
- Constants
- Variables
- func ApiKeyMiddleware(cfg APIKeyConfig, logger *logging.Logger) (func(handler http.Handler) http.Handler, error)
- func ConvertToFloat64(value interface{}) (float64, error)
- func DeriveKeyPair(mnemonic string, password string) (publicKey, privateKey []byte, err error)
- func GenerateMnemonic() (string, error)
- func GenerateRandomPassword() (string, error)
- func GenerateWalletAddress(publicKey []byte) (string, error)
- func GetType(i interface{}) string
- func GetUserIP(r *http.Request) string
- func IntToBytes(n int) []byte
- func LocalStorageAvailable() bool
- func LocalWalletCount() (count int, err error)
- func LocalWalletList() error
- func Name() string
- func NewLocalStorage(dataPath string) error
- func NewNode(opts *NodeOptions) error
- func PrettyPrint(v interface{}) string
- func RespondError(w http.ResponseWriter, statusCode int, message string)
- func SecureRandomInt(max int) int
- func SendGmail(to, subject, body string, cfg *Config) error
- func ValidateAddress(address string) error
- func VerifySignature(message []byte, signature []byte, publicKey *ecdsa.PublicKey) bool
- func Version() string
- type API
- type APIKeyConfig
- type APIKeyList
- type Address
- type Arguments
- func (a *Arguments) GetBool(name string) bool
- func (a *Arguments) GetFloat64(name string) float64
- func (a *Arguments) GetInt(name string) int
- func (a *Arguments) GetInt64(name string) int64
- func (a *Arguments) GetString(name string) string
- func (a *Arguments) Parse() error
- func (a *Arguments) PrintUsage()
- func (a *Arguments) Register(name string, desc string, defaultVal interface{})
- type Bank
- type BigInt
- func (b *BigInt) Abs() *BigInt
- func (b *BigInt) Add(other *BigInt) *BigInt
- func (b *BigInt) And(other *BigInt) *BigInt
- func (b *BigInt) Base64() string
- func (b *BigInt) Bytes() []byte
- func (b *BigInt) Compare(other *BigInt) int
- func (b *BigInt) Divide(other *BigInt) *BigInt
- func (b *BigInt) IsEqual(other *BigInt) bool
- func (b *BigInt) IsGreaterThan(other *BigInt) bool
- func (b *BigInt) IsLessThan(other *BigInt) bool
- func (b *BigInt) IsNegative() bool
- func (b *BigInt) IsPositive() bool
- func (b *BigInt) IsZero() bool
- func (b *BigInt) Modulo(other *BigInt) *BigInt
- func (b *BigInt) Multiply(other *BigInt) *BigInt
- func (b *BigInt) Neg() *BigInt
- func (b *BigInt) Not() *BigInt
- func (b *BigInt) Or(other *BigInt) *BigInt
- func (b *BigInt) Random() (*BigInt, error)
- func (b *BigInt) Shl(n uint) *BigInt
- func (b *BigInt) Shr(n uint) *BigInt
- func (b *BigInt) String() string
- func (b *BigInt) Subtract(other *BigInt) *BigInt
- func (b *BigInt) Xor(other *BigInt) *BigInt
- type Block
- func (b *Block) AdjustDifficulty(previousBlock *Block, targetBlockTime time.Duration) uint32
- func (b *Block) Bytes() []byte
- func (b *Block) CalculateBlockReward(currentBlockHeight int64) float64
- func (b *Block) CalculateHash() string
- func (b *Block) CalculateMerkleRoot() []byte
- func (b *Block) CalculateTotalFees() float64
- func (b *Block) CanAddTransaction(tx Transaction) bool
- func (b *Block) CreateBloomFilter() *BloomFilter
- func (b *Block) GetTransactions(id string) []Transaction
- func (b *Block) Mine(difficulty uint)
- func (b *Block) Serialize() ([]byte, error)
- func (b *Block) String() string
- func (b *Block) Validate(previousBlock *Block) error
- type BlockHeader
- type BlockQueryCriteria
- type Blockchain
- func (bc *Blockchain) AddTransaction(transaction Transaction)
- func (bc *Blockchain) CalculateTotalSupply() float64
- func (bc *Blockchain) DisplayStatus()
- func (bc *Blockchain) GenerateGenesisBlock(txs []Transaction)
- func (bc *Blockchain) GetBalance(address string) float64
- func (bc *Blockchain) GetBlockByHash(hash string) *Block
- func (bc *Blockchain) GetBlockByIndex(index int64) *Block
- func (bc *Blockchain) GetBlockCount() int
- func (bc *Blockchain) GetBlockchainInfo() BlockchainInfo
- func (bc *Blockchain) GetConfig() *Config
- func (bc *Blockchain) GetLatestBlock() *Block
- func (bc *Blockchain) GetMempoolSize() int
- func (bc *Blockchain) GetPendingTransactions() []Transaction
- func (bc *Blockchain) GetTransactionByID(id string) Transaction
- func (bc *Blockchain) GetTransactionHistory(address string) []Transaction
- func (bc *Blockchain) HasTransaction(id *PUID) bool
- func (bc *Blockchain) Load() error
- func (bc *Blockchain) LoadExistingBlocks() error
- func (bc *Blockchain) Mine(block *Block, difficulty int) *Block
- func (bc *Blockchain) RemoveTransaction(id string) bool
- func (bc *Blockchain) Run(difficulty int)
- func (bc *Blockchain) Save() error
- func (bc *Blockchain) UpdateConfig(newConfig *Config) error
- func (bc *Blockchain) ValidateChain() error
- func (bc *Blockchain) VerifySignature(tx Transaction) error
- type BlockchainData
- type BlockchainInfo
- type BlockchainPersistData
- type BloomFilter
- type Coinbase
- type Config
- type EncryptionParams
- type ErrorResponse
- type FIFOQueue
- func (q *FIFOQueue) Dequeue() string
- func (q *FIFOQueue) Enqueue(element string)
- func (q *FIFOQueue) Exists(entry string) bool
- func (q *FIFOQueue) Find(s string) string
- func (q *FIFOQueue) Get() *Index
- func (q *FIFOQueue) IsEmpty() bool
- func (q *FIFOQueue) Len() int
- func (q *FIFOQueue) Set(index *Index)
- type Flag
- func (f *Flag) Bool(name string, value bool, usage string) *bool
- func (f *Flag) Float64(name string, value float64, usage string) *float64
- func (f *Flag) Int(name string, value int, usage string) *int
- func (f *Flag) Int64(name string, value int64, usage string) *int64
- func (f *Flag) String(name string, value string, usage string) *string
- type HTML5
- type Index
- type IndexEntry
- type LocalStorage
- type LocalStorageOptions
- type MerkleNode
- type MerkleTree
- type Message
- type Node
- type NodeData
- type NodeInfo
- type NodeOptions
- type NodePersistData
- type NodeStatus
- type P2P
- func (p *P2P) AddTransaction(tx P2PTransaction)
- func (p *P2P) Broadcast(tx P2PTransaction) error
- func (p *P2P) BroadcastMessage(msg P2PTransaction) error
- func (p *P2P) BroadcastStatus(node *Node, status string) error
- func (p *P2P) ConnectToSeedNode(address string) error
- func (p *P2P) HasTransaction(id *PUID) bool
- func (p *P2P) IsRegistered(nodeID string) bool
- func (p *P2P) IsRunning() bool
- func (p *P2P) ProcessQueue()
- func (p *P2P) RegisterNode(node *Node) error
- func (p *P2P) SetAsSeedNode()
- func (p *P2P) Start() error
- func (p *P2P) Stop() error
- type P2PTransaction
- type P2PTransactionState
- type PEM
- func (p *PEM) AsBytes(s string) []byte
- func (p *PEM) Decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey)
- func (p *PEM) Encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string)
- func (p *PEM) GetPrivate() string
- func (p *PEM) GetPublic() string
- type PUID
- func (p *PUID) Base64() string
- func (p *PUID) Bytes() []byte
- func (p *PUID) Equal(other *PUID) bool
- func (p *PUID) GetAppID() *BigInt
- func (p *PUID) GetAssetID() *BigInt
- func (p *PUID) GetOrganizationID() *BigInt
- func (p *PUID) GetUserID() *BigInt
- func (p *PUID) IsAppID(appID *BigInt) bool
- func (p *PUID) IsAssetID(assetID *BigInt) bool
- func (p *PUID) IsOrganiztionID(organizationID *BigInt) bool
- func (p *PUID) IsUserID(userID *BigInt) bool
- func (p *PUID) IsZero() bool
- func (p *PUID) SetAssetID(assetID *BigInt)
- func (p *PUID) String() string
- type Persist
- type State
- type TXLookupManager
- type Transaction
- type TransactionQueryCriteria
- type TransactionStatus
- type Tx
- func (t *Tx) Bytes() []byte
- func (t *Tx) EstimateFee(feePerByte float64) float64
- func (t *Tx) GetFee() float64
- func (t *Tx) GetHash() string
- func (t *Tx) GetID() string
- func (t *Tx) GetPriority() int
- func (t *Tx) GetProtocol() string
- func (t *Tx) GetSenderWallet() *Wallet
- func (t *Tx) GetSignature() string
- func (t *Tx) GetStatus() TransactionStatus
- func (t *Tx) Hash() string
- func (t *Tx) Hex() string
- func (t *Tx) IsCoinbase() bool
- func (t *Tx) JSON() string
- func (t *Tx) Log() string
- func (t *Tx) Process() string
- func (t *Tx) Send(bc *Blockchain) error
- func (t *Tx) SetPriority(priority int)
- func (t *Tx) SetStatus(status TransactionStatus)
- func (t *Tx) Sign(privPEM []byte) (string, error)
- func (t *Tx) Size() int
- func (t *Tx) String() string
- func (t *Tx) Validate() error
- func (t *Tx) Verify(pubKey []byte, sign string) (bool, error)
- type Vault
- type Wallet
- func (w *Wallet) Close(passphrase string) error
- func (w *Wallet) GetAddress() string
- func (w *Wallet) GetBalance() float64
- func (w *Wallet) GetData(key string) (interface{}, error)
- func (w *Wallet) GetTags() []string
- func (w *Wallet) GetWalletName() string
- func (w *Wallet) Lock(passphrase string) error
- func (w *Wallet) Open(passphrase string) error
- func (w *Wallet) PrivateBytes() ([]byte, error)
- func (w *Wallet) PrivateKey() (*ecdsa.PrivateKey, error)
- func (w *Wallet) PrivatePEM() string
- func (w *Wallet) PublicBytes() ([]byte, error)
- func (w *Wallet) PublicKey() (*ecdsa.PublicKey, error)
- func (w *Wallet) PublicPEM() string
- func (w *Wallet) SendTransaction(to string, tx Transaction, bc *Blockchain) (*Transaction, error)
- func (w *Wallet) SetData(key string, value interface{}) error
- func (w *Wallet) Unlock(passphrase string) error
- type WalletOptions
Constants ¶
const ( // InitialDifficulty is the starting difficulty for mining blocks InitialDifficulty = 4 // BlockRewardHalvingInterval is the number of blocks between each halving of the block reward BlockRewardHalvingInterval = 210000 // InitialBlockReward is the initial reward for mining a block InitialBlockReward = 50.0 )
const ( // Blockchain Identification BlockchainName = "Go Basic Blockchain" BlockchainSymbol = "GBB" BlockchainVersion = "0.1.0" BlockhainOrganizationID = 1 // 1 is reserved for this blockchain "Go Basic Blockchain" BlockchainAdminUserID = 1 BlockchainAppID = 1 // 1 is reserved for this blockchain's Core BlockchainDevAssetID = 1 BlockchainMinerAssetID = 2 MaxBlockSize = 1000000 // Maximum block size in bytes (1MB) // Feature Flags EnableAPI = true // Protocol Versions TransactionProtocolVersion = "1.0" )
const ( PersistProtocolID = "PERSIST" BankProtocolID = "BANK" MessageProtocolID = "MESSAGE" CoinbaseProtocolID = "COINBASE" ChainProtocolID = "CHAIN" )
Protocol IDs
const TransactionVersion = 1
TransactionVersion represents the current version of the transaction structure.
Variables ¶
var ( // These are required and will be created when a new blockchain is created ThisBlockchainOrganizationID = NewBigInt(0) ThisBlockchainAppID = NewBigInt(0) ThisBlockchainAdminUserID = NewBigInt(0) ThisBlockchainDevAssetID = NewBigInt(0) ThisBlockchainMinerID = NewBigInt(0) )
var AvailableProtocols = []string{ CoinbaseProtocolID, BankProtocolID, MessageProtocolID, PersistProtocolID, ChainProtocolID, }
AvailableProtocols is a list of all available protocols
var RequiredWalletProperties = []string{
"name",
"tags",
"balance",
"public_key",
"private_key",
}
RequiredWalletProperties is a list of required properties for a wallet. This list defines the minimum set of properties that a wallet must have in order to be considered valid. The properties include the wallet name, tags, balance, public key, and private key.
Functions ¶
func ApiKeyMiddleware ¶
func ApiKeyMiddleware(cfg APIKeyConfig, logger *logging.Logger) (func(handler http.Handler) http.Handler, error)
ApiKeyMiddleware is a middleware function that checks for a valid API key in the request header. It takes an APIKeyConfig and a logging.Logger as input, and returns a middleware function that can be used to wrap an http.Handler.
The middleware first checks if the requested path is public (using the isPublicPath function), and if so, skips the API key check and calls the next handler.
If the path is secured, the middleware extracts the API key from the request header using the bearerToken function, and then checks if the API key is valid by looking it up in the decodedAPIKeys map. If the API key is not valid, the middleware responds with a 401 Unauthorized error.
If the API key is valid, the middleware calls the next handler with the original request context.
func ConvertToFloat64 ¶
ConvertToFloat64 converts various types to float64. It supports the following types: float64, float32, int, int64, int32, and string. If the input is a string, it attempts to parse it as a float64. If the conversion is successful, it returns the float64 value and a nil error. If the conversion fails or the type is unsupported, it returns 0 and an error.
Parameters: - value: The input value of type interface{} to be converted.
Returns: - float64: The converted float64 value. - error: An error if the conversion fails or the type is unsupported.
func DeriveKeyPair ¶
DeriveKeyPair derives a public/private key pair from a given mnemonic passphrase.
func GenerateMnemonic ¶
GenerateMnemonic generates a new 12-word mnemonic passphrase.
func GenerateRandomPassword ¶
GenerateRandomPassword generates a random password that meets the following requirements: - Length between 12 and 24 characters - At least 2 uppercase letters - At least 2 lowercase letters - At least 2 digits - At least 2 special characters
If the generated password does not meet these requirements, an error is returned.
func GenerateWalletAddress ¶
GenerateWalletAddress generates a wallet address from a given public key.
func GetType ¶
func GetType(i interface{}) string
GetType returns the type name of the provided interface{} value. If the value is a pointer, it returns the type name prefixed with "*".
func GetUserIP ¶
GetUserIP returns the IP address of the client making the HTTP request. It handles cases where the request comes through a proxy by parsing the X-Forwarded-For header. If the header is not set, it falls back to the RemoteAddr field of the request.
func IntToBytes ¶
IntToBytes converts an integer to a byte slice in big-endian encoding. The resulting byte slice will always be 4 bytes long, regardless of the value of the input integer.
func LocalStorageAvailable ¶
func LocalStorageAvailable() bool
LocalStorageAvailable returns a boolean indicating whether the LocalStorage instance has been initialized. This function can be used to check if the local storage data persist manager is available for use.
func LocalWalletCount ¶
LocalWalletCount returns the number of wallets in the wallet folder.
func LocalWalletList ¶
func LocalWalletList() error
LocalWalletList searches the wallet folder for all JSON files, loads each one, and displays the Wallet ID, Name, Address, and Tags.
func NewLocalStorage ¶
NewLocalStorage creates a new instance of the LocalStorage struct, which is the data persist manager using the Go standard library's file system. If dataPath is an empty string, it will use the default data path "./data". The function also performs any initial setup or data loading if needed.
If local storage has already been initialized, this function will return an error.
func NewNode ¶
func NewNode(opts *NodeOptions) error
func PrettyPrint ¶
func PrettyPrint(v interface{}) string
PrettyPrint takes an arbitrary interface{} value and returns a formatted string representation of the value. It uses json.MarshalIndent to pretty-print the JSON encoding of the value, and prepends the type name of the value.
func RespondError ¶
func RespondError(w http.ResponseWriter, statusCode int, message string)
RespondError sends an error response with the given status code and message.
func SecureRandomInt ¶
func SendGmail ¶
SendGmail sends an email using the provided Gmail account configuration.
The function takes the recipient email address, subject, and body of the email, as well as a Config struct containing the Gmail account email and password.
It first validates the provided configuration and email addresses, then constructs the email message and sends it using the Gmail SMTP server.
If any errors occur during the process, the function will return an error.
func ValidateAddress ¶
ValidateAddress validates the provided Ethereum address string. It decodes the address and verifies that the length of the decoded bytes is 32. If the address is invalid, it returns an error.
func VerifySignature ¶
VerifySignature verifies the provided signature against the given message and public key. It returns true if the signature is valid, and false otherwise.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API is the blockchain API.
type APIKeyConfig ¶
type APIKeyConfig struct { APIKeyHeader string APIKeys APIKeyList }
APIKeyConfig is a configuration struct that holds the API key header name and a map of API keys. The APIKeys field is a map of API keys to their corresponding values, used to store and manage API keys.
type APIKeyList ¶
APIKeyList is a map of API keys to their corresponding values. This type is used to store and manage API keys.
type Address ¶
Address represents a blockchain address. It contains the raw address string and a prepended version of the address.
func NewAddress ¶
NewAddress creates a new Address with the given raw address and blockchain symbol. The raw address is prepended with the blockchain symbol to create the prepended address.
func (*Address) GetAddressHash ¶
GetAddressHash calculates and returns the SHA-256 hash of the prepended address.
func (*Address) GetPrependedAddress ¶
GetPrependedAddress returns the address with the blockchain symbol prepended. This method returns the full address string that includes the blockchain symbol prepended to the raw address.
func (*Address) GetRawAddress ¶
GetRawAddress returns the raw address string of the Address.
type Arguments ¶
Arguments handles parsing arguments and displaying usage information
func (*Arguments) GetFloat64 ¶
GetFloat64 returns the float64 value of the named flag
func (*Arguments) PrintUsage ¶
func (a *Arguments) PrintUsage()
PrintUsage prints usage information for all registered arguments
type Bank ¶
Bank is a transaction that represents a bank transfer. It embeds the Tx struct and adds an Amount field to represent the transfer amount.
func NewBankTransaction ¶
NewBankTransaction creates a new Bank transaction. It takes a from wallet, a to wallet, and an amount to transfer. It first creates a new Transaction using the BankProtocolID, the from wallet, and the to wallet. It then checks if the from wallet has enough balance to cover the transfer amount plus the transaction fee. If the balance is sufficient, it returns a new Bank transaction with the created Transaction and the transfer amount. If the balance is insufficient, it returns an error.
func (*Bank) Process ¶
Process processes the bank transaction. It first checks if the "From" wallet has enough balance to cover the transaction amount plus the transaction fee. If the balance is sufficient, it subtracts the amount and fee from the "From" wallet and adds the amount to the "To" wallet. It returns a formatted string indicating the success or failure of the transaction.
type BigInt ¶
type BigInt struct {
Val int64
}
bigint -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64-bit)
func NewBigIntFromBytes ¶
NewBigIntFromBytes creates a new BigInt instance from a byte slice.
func NewBigIntFromString ¶
NewBigIntFromString creates a new BigInt instance from a string representation. If the input string is base64-encoded, it will be decoded first.
func NewRandomBigInt ¶
NewRandomBigInt creates a new BigInt instance with a random value.
func (*BigInt) IsGreaterThan ¶
IsGreaterThan returns true if the current BigInt is greater than the given BigInt.
func (*BigInt) IsLessThan ¶
IsLessThan returns true if the current BigInt is less than the given BigInt.
func (*BigInt) IsNegative ¶
IsNegative returns true if the BigInt is negative.
func (*BigInt) IsPositive ¶
IsPositive returns true if the BigInt is positive.
func (*BigInt) Random ¶
RandomBigInt returns a cryptographically secure random BigInt incorporating the current time in nanoseconds. It generates a random 64-bit integer and combines it with the current time in nanoseconds to create a new BigInt. This function is useful for generating unique, random BigInt values.
func (*BigInt) Shr ¶
Bitwise shift right operation Shr shifts the bits of the BigInt to the right by the given number of positions. It returns a new BigInt with the shifted bits.
type Block ¶
type Block struct { Header BlockHeader `json:"header"` Transactions []Transaction `json:"transactions"` Index big.Int `json:"index"` // Maintain original Index for backwards compatibility Hash string `json:"hash"` // Maintain original Hash for backwards compatibility // contains filtered or unexported fields }
Block represents a block in the blockchain.
func DeserializeBlock ¶
DeserializeBlock deserializes a byte slice into a Block.
func NewBlock ¶
func NewBlock(transactions []Transaction, previousHash string) *Block
NewBlock creates a new block with the given transactions and previous hash.
func (*Block) AdjustDifficulty ¶
AdjustDifficulty adjusts the mining difficulty based on the time taken to mine recent blocks.
func (*Block) CalculateBlockReward ¶
CalculateBlockReward calculates the block reward based on the current block height.
func (*Block) CalculateHash ¶
CalculateHash calculates and returns the hash of the block.
func (*Block) CalculateMerkleRoot ¶
CalculateMerkleRoot calculates the Merkle root of the block's transactions.
func (*Block) CalculateTotalFees ¶
CalculateTotalFees calculates the total transaction fees in the block.
func (*Block) CanAddTransaction ¶
func (b *Block) CanAddTransaction(tx Transaction) bool
CanAddTransaction checks if adding a new transaction would exceed the maximum block size.
func (*Block) CreateBloomFilter ¶
func (b *Block) CreateBloomFilter() *BloomFilter
CreateBloomFilter creates a Bloom filter for quick transaction lookups within the block.
func (*Block) GetTransactions ¶
func (b *Block) GetTransactions(id string) []Transaction
GetTransactions returns the transactions in the block that match the given transaction ID. If an ID is provided, it returns a slice containing only the transaction with the matching ID. If no ID is provided, it returns all the transactions in the block.
type BlockHeader ¶
type BlockHeader struct { Version int32 `json:"version"` PreviousHash string `json:"previousHash"` MerkleRoot []byte `json:"merkleRoot"` Timestamp time.Time `json:"timestamp"` Difficulty uint32 `json:"difficulty"` Nonce uint32 `json:"nonce"` }
BlockHeader represents the header of a block in the blockchain.
type BlockQueryCriteria ¶
type BlockQueryCriteria struct {
Number int
}
BlockQueryCriteria represents the criteria for querying blocks.
type Blockchain ¶
type Blockchain struct { Blocks []*Block // Slice of blocks in the blockchain TransactionQueue []Transaction // Queue of transactions to be added to the blockchain TXLookup *TXLookupManager // Map of Block Number/Index (Key) and Transaction ID (Value) CurrentBlockIndex int // Current block index NextBlockIndex int // Next block index AvgTxsPerBlock float64 // Average number of transactions per block State *State // Current state of the blockchain // contains filtered or unexported fields }
Blockchain is the main struct that represents the blockchain.
func NewBlockchain ¶
func NewBlockchain(cfg *Config) *Blockchain
NewBlockchain creates a new instance of the Blockchain struct with the provided configuration.
func (*Blockchain) AddTransaction ¶
func (bc *Blockchain) AddTransaction(transaction Transaction)
AddTransaction adds a new transaction to the transaction queue.
func (*Blockchain) CalculateTotalSupply ¶
func (bc *Blockchain) CalculateTotalSupply() float64
CalculateTotalSupply calculates the total supply of tokens in the blockchain.
func (*Blockchain) DisplayStatus ¶
func (bc *Blockchain) DisplayStatus()
DisplayStatus displays the current status of the blockchain.
func (*Blockchain) GenerateGenesisBlock ¶
func (bc *Blockchain) GenerateGenesisBlock(txs []Transaction)
GenerateGenesisBlock generates the genesis block if there are no existing blocks.
func (*Blockchain) GetBalance ¶
func (bc *Blockchain) GetBalance(address string) float64
GetBalance returns the balance of a given wallet address.
func (*Blockchain) GetBlockByHash ¶
func (bc *Blockchain) GetBlockByHash(hash string) *Block
GetBlockByHash returns a block with the given hash.
func (*Blockchain) GetBlockByIndex ¶
func (bc *Blockchain) GetBlockByIndex(index int64) *Block
GetBlockByIndex returns a block at the given index.
func (*Blockchain) GetBlockCount ¶
func (bc *Blockchain) GetBlockCount() int
GetBlockCount returns the total number of blocks in the blockchain.
func (*Blockchain) GetBlockchainInfo ¶
func (bc *Blockchain) GetBlockchainInfo() BlockchainInfo
GetBlockchainInfo returns general information about the blockchain.
func (*Blockchain) GetConfig ¶
func (bc *Blockchain) GetConfig() *Config
GetConfig returns the configuration used to create the Blockchain instance.
func (*Blockchain) GetLatestBlock ¶
func (bc *Blockchain) GetLatestBlock() *Block
GetLatestBlock returns the latest block in the blockchain.
func (*Blockchain) GetMempoolSize ¶
func (bc *Blockchain) GetMempoolSize() int
GetMempoolSize returns the number of transactions in the mempool (transaction queue).
func (*Blockchain) GetPendingTransactions ¶
func (bc *Blockchain) GetPendingTransactions() []Transaction
GetPendingTransactions returns all pending transactions in the queue.
func (*Blockchain) GetTransactionByID ¶
func (bc *Blockchain) GetTransactionByID(id string) Transaction
GetTransactionByID returns a transaction with the given ID.
func (*Blockchain) GetTransactionHistory ¶
func (bc *Blockchain) GetTransactionHistory(address string) []Transaction
GetTransactionHistory returns the transaction history for a given wallet address.
func (*Blockchain) HasTransaction ¶
func (bc *Blockchain) HasTransaction(id *PUID) bool
HasTransaction checks if a transaction with the given ID exists in the blockchain.
func (*Blockchain) Load ¶
func (bc *Blockchain) Load() error
Load loads the blockchain state from disk.
func (*Blockchain) LoadExistingBlocks ¶
func (bc *Blockchain) LoadExistingBlocks() error
LoadExistingBlocks loads any existing blocks from disk and appends them to the blockchain.
func (*Blockchain) Mine ¶
func (bc *Blockchain) Mine(block *Block, difficulty int) *Block
Mine attempts to mine a new block for the blockchain.
func (*Blockchain) RemoveTransaction ¶
func (bc *Blockchain) RemoveTransaction(id string) bool
RemoveTransaction removes a transaction from the pending queue.
func (*Blockchain) Run ¶
func (bc *Blockchain) Run(difficulty int)
Run is a long-running function that manages the blockchain.
func (*Blockchain) Save ¶
func (bc *Blockchain) Save() error
Save saves the blockchain state to disk.
func (*Blockchain) UpdateConfig ¶
func (bc *Blockchain) UpdateConfig(newConfig *Config) error
UpdateConfig updates the blockchain configuration.
func (*Blockchain) ValidateChain ¶
func (bc *Blockchain) ValidateChain() error
ValidateChain validates the entire blockchain.
func (*Blockchain) VerifySignature ¶
func (bc *Blockchain) VerifySignature(tx Transaction) error
VerifySignature verifies the signature of the given transaction.
type BlockchainData ¶
BlockchainData represents the data persisted for a blockchain. It contains an ID and a Version field, along with any additional fields as needed.
type BlockchainInfo ¶
type BlockchainInfo struct { Version string `json:"version,omitempty"` Name string `json:"name,omitempty"` Symbol string `json:"symbol,omitempty"` BlockTime int `json:"block_time,omitempty"` Difficulty int `json:"difficulty,omitempty"` Fee float64 `json:"transaction_fee,omitempty"` }
BlockchainInfo represents information about a blockchain, including its version, name, symbol, block time, difficulty, and transaction fee.
type BlockchainPersistData ¶
type BlockchainPersistData struct { TXLookup *Index `json:"tx_lookup"` CurrBlockIndex *int `json:"current_block_index"` NextBlockIndex *int `json:"next_block_index"` }
BlockchainPersistData represents the data that is persisted for a blockchain to disk.
func (*BlockchainPersistData) String ¶
func (b *BlockchainPersistData) String() string
String returns a string representation of the BlockchainPersistData.
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter represents a Bloom filter for quick transaction lookups.
func (*BloomFilter) Add ¶
func (bf *BloomFilter) Add(data []byte)
Add adds data to the Bloom filter.
func (*BloomFilter) Contains ¶
func (bf *BloomFilter) Contains(data []byte) bool
Contains checks if the Bloom filter possibly contains the given data.
type Coinbase ¶
type Coinbase struct { Tx BlockchainName string BlockchainSymbol string BlockTime int Difficulty int TransactionFee float64 MinerRewardPCT float64 MinerAddress string DevRewardPCT float64 DevAddress string FundWalletAmount float64 TokenCount int64 TokenPrice float64 AllowNewTokens bool }
Coinbase represents a coinbase transaction, which is a special type of transaction that is used to reward miners for mining a new block. It contains information about the block, the miner's reward, and any additional rewards or fees.
func NewCoinbaseTransaction ¶
NewCoinbaseTransaction creates a new coinbase transaction. It takes a from wallet, a to wallet, and a configuration object as input. The function returns a new Coinbase transaction and an error if any. The Coinbase transaction contains information about the block, the miner's reward, and any additional rewards or fees.
type Config ¶
type Config struct { BlockchainName string BlockchainSymbol string BlockTime int Difficulty int TransactionFee float64 MinerRewardPCT float64 MinerAddress string DevRewardPCT float64 DevAddress string APIHostName string P2PHostName string EnableAPI bool FundWalletAmount float64 TokenCount int64 TokenPrice float64 AllowNewTokens bool DataPath string GMailEmail string GMailPassword string Domain string Version string // New field: Configuration version MaxBlockSize int // New field: Maximum block size in bytes MinTransactionFee float64 // New field: Minimum transaction fee IsSeed bool // New field: Is this a seed node SeedAddress string // New field: Address of the seed node to connect to // contains filtered or unexported fields }
Config is the configuration for the blockchain.
func NewConfig ¶
func NewConfig() *Config
NewConfig creates a new configuration object with default values.
func (*Config) PromptWalletInfo ¶
PromptWalletInfo prompts the user to enter wallet information.
func (*Config) PromptYesNo ¶
PromptYesNo prompts the user with a given question and returns a bool value based on their response.
type EncryptionParams ¶
type EncryptionParams struct { SaltSize int // Size of the salt used for key derivation NonceSize int // Size of the nonce used for encryption }
EncryptionParams holds the encryption parameters for the private key.
func NewDefaultEncryptionParams ¶
func NewDefaultEncryptionParams() *EncryptionParams
NewDefaultEncryptionParams creates a new EncryptionParams struct with default values. The default salt size is 32 bytes and the default nonce size is 12 bytes.
func NewEncryptionParams ¶
func NewEncryptionParams(saltSize, nonceSize int) *EncryptionParams
NewEncryptionParams creates a new EncryptionParams struct with the specified salt and nonce sizes. The salt size and nonce size are used to configure the encryption parameters for a wallet's private key.
type ErrorResponse ¶
type ErrorResponse struct {
Message string `json:"message"`
}
ErrorResponse represents the structure of an error response.
type FIFOQueue ¶
type FIFOQueue struct {
// contains filtered or unexported fields
}
FIFOQueue represents a FIFO queue with a maximum capacity.
func NewFIFOQueue ¶
NewFIFOQueue creates a new FIFO queue with the specified capacity.
func (*FIFOQueue) Dequeue ¶
Dequeue removes and returns the oldest element from the front of the queue. If the queue is empty, an empty string is returned.
func (*FIFOQueue) Enqueue ¶
Enqueue adds an element to the back of the queue. If the queue is already at its maximum capacity, the oldest element is removed.
func (*FIFOQueue) Find ¶
Find returns the first entry in the Index that contains the string s, or an empty string if no match is found.
type Flag ¶
type Flag struct { Name string // name of the argument Description string // description of the argument Value interface{} // value of the argument }
Flag contains information for every argument
type HTML5 ¶
type HTML5 struct { EndableUsers bool // contains filtered or unexported fields }
HTML5 is a struct to hold the HTML5 settings & methods
var ( // HTML is the HTML5 object HTML *HTML5 )
func (*HTML5) RenderFormLogin ¶
RenderFormLogin returns string content representing a valid HTML5 login form
func (*HTML5) RenderPage ¶
RenderPage returns string content representing a valid HTML5 page
func (*HTML5) RenderPageHeader ¶
RenderPageHeader returns string content representing a valid HTML5 page header
func (*HTML5) RenderPageLogin ¶
RenderPageLogin returns string content representing a valid HTML5 page with the login form centered on the page
func (*HTML5) RenderPageNotImplemented ¶
RenderPageNotImplemented returns string content representing a valid HTML5 page with a message that the page is not yet implemented
type Index ¶
type Index []string // Tx Lookup via BlockID (Key) and TxID (Value)
Index is a map of Block Number/Index (Key) and Transaction ID (Value) that is stored in memory and persisted to disk. Example 1 => "dbc74a05-703b-49e2-b607-37153ec6ff9e" The Block index is a big.Int (8 bytes) and the Transaction ID is a UUID (16 bytes) for a table record size of 24 bytes. The last 64k Transactions will be stored in memory for fast lookup. Any Transactions beyond that will be looked up via disk. Uses indexCacheSize (defined in const.go) is the size of the block/transaction index cache (1,572,864 bytes or 1.5 MB)
type IndexEntry ¶
IndexEntry is a struct that contains the blockNumber, txID and txHash for a transaction. It is used for both searching and returning results.
type LocalStorage ¶
type LocalStorage struct {
// contains filtered or unexported fields
}
LocalStorage represents the data persist manager using the Go standard library's file system. The dataPath field specifies the path where all data is stored.
func GetLocalStorage ¶
func GetLocalStorage() (*LocalStorage, error)
/ GetLocalStorage returns the singleton instance of the LocalStorage struct, which provides access to the / data persist manager using the Go standard library's file system. If local storage has not been / initialized, this function will return an error.
func (*LocalStorage) Find ¶
func (ls *LocalStorage) Find(criteria interface{}) ([]interface{}, error)
Find searches for data in the LocalStorage based on the given criteria. It supports two types of criteria: BlockQueryCriteria and TransactionQueryCriteria. For BlockQueryCriteria, it will query and return the matching Blocks. For TransactionQueryCriteria, it will query and return the matching Transactions. If the criteria type is unsupported, an error is returned.
func (*LocalStorage) Get ¶
func (ls *LocalStorage) Get(key string, v interface{}) error
Get retrieves the value associated with the given key from the LocalStorage. It decodes the JSON data from the file corresponding to the type of the provided value. If the file does not exist or the JSON data cannot be decoded, an error is returned.
func (*LocalStorage) Set ¶
func (ls *LocalStorage) Set(key string, v interface{}) error
Set stores the provided value under the given key in the LocalStorage. It creates or truncates the file corresponding to the type of the provided value, and encodes the value as JSON data in the file. If an error occurs while creating the file or encoding the data, an error is returned.
type LocalStorageOptions ¶
type LocalStorageOptions struct { DataPath string // path where all data is stored NodePrivateKey string // private key of the node (if you want to encrypt data) NumCacheItems int // number of items to cache in memory. this applies to all type (blocks, transactions, etc) }
LocalStorageOptions represents the options for the LocalStorage data persist manager. DataPath specifies the path where all data is stored. NodePrivateKey specifies the private key of the node, which can be used to encrypt data. NumCacheItems specifies the number of items to cache in memory, which applies to all types (blocks, transactions, etc).
type MerkleNode ¶
type MerkleNode struct { Left *MerkleNode Right *MerkleNode Data []byte }
MerkleNode represents a node in the Merkle tree.
func NewMerkleNode ¶
func NewMerkleNode(left, right *MerkleNode, data []byte) *MerkleNode
NewMerkleNode creates a new Merkle node.
type MerkleTree ¶
type MerkleTree struct {
Root *MerkleNode
}
MerkleTree represents a Merkle tree of transactions.
func NewMerkleTree ¶
func NewMerkleTree(data [][]byte) *MerkleTree
NewMerkleTree creates a new Merkle tree from a list of data.
type Message ¶
Message is a transaction that represents a message sent from one user to another.
func NewMessageTransaction ¶
NewMessageTransaction creates a new message transaction.
type Node ¶
type Node struct { sync.Mutex LastSeen time.Time Status string ID string Config *Config Blockchain *Blockchain API *API P2P *P2P Wallet *Wallet // contains filtered or unexported fields }
Node is a node in the blockchain network.
func (*Node) ProcessP2PTransaction ¶
func (n *Node) ProcessP2PTransaction(tx P2PTransaction) error
ProcessP2PTransaction processes a P2PTransaction received from the P2P network.
type NodeOptions ¶
type NodeOptions struct { EnvName string DataPath string Config *Config IsSeed bool SeedAddress string }
NodeOptions is the options for a node.
func DefaultNodeOptions ¶
func DefaultNodeOptions() *NodeOptions
func NewNodeOptions ¶
func NewNodeOptions(envName string, path string, cfg *Config) *NodeOptions
NewNodeOptions creates a new NodeOptions instance.
type NodePersistData ¶
NodePersistData is the data that is persisted for a node to disk.
type NodeStatus ¶
type P2P ¶
type P2P struct {
// contains filtered or unexported fields
}
P2P represents the P2P network.
func (*P2P) AddTransaction ¶
func (p *P2P) AddTransaction(tx P2PTransaction)
AddTransaction adds a new transaction to the processing queue.
func (*P2P) Broadcast ¶
func (p *P2P) Broadcast(tx P2PTransaction) error
Broadcast broadcasts a P2PTransaction to nodes in the network.
func (*P2P) BroadcastMessage ¶
func (p *P2P) BroadcastMessage(msg P2PTransaction) error
BroadcastMessage broadcasts a p2p message to all nodes in the network
func (*P2P) ConnectToSeedNode ¶
func (*P2P) HasTransaction ¶
HasTransaction checks if the P2P network has a specified transaction.
func (*P2P) IsRegistered ¶
IsRegistered returns true if the given node is registered with the P2P network.
func (*P2P) ProcessQueue ¶
func (p *P2P) ProcessQueue()
ProcessQueue processes the pending transactions in the queue.
func (*P2P) RegisterNode ¶
RegisterNode registers a new node with the P2P network.
func (*P2P) SetAsSeedNode ¶
func (p *P2P) SetAsSeedNode()
type P2PTransaction ¶
type P2PTransaction struct { Tx Target string Action string State P2PTransactionState Data interface{} }
P2PTransaction represents a transaction to be processed.
type P2PTransactionState ¶
type P2PTransactionState int
P2PTransactionState represents the current state of a P2P transaction
const ( P2PTxNone P2PTransactionState = iota P2PTxQueued P2PTxPnd13 P2PTxValid P2PTxPnd23 P2PTxFinal P2PTxPnd P2PTxArchived )
func P2PTransactionStateFromString ¶
func P2PTransactionStateFromString(s string) (P2PTransactionState, error)
func (*P2PTransactionState) Next ¶
func (p *P2PTransactionState) Next()
func (P2PTransactionState) String ¶
func (p P2PTransactionState) String() string
type PEM ¶
PEM is a struct that holds the PEM encoded private and public keys for a cryptographic key pair. The PrivateKey field contains the PEM encoded private key, and the PublicKey field contains the PEM encoded public key.
func NewPEM ¶
func NewPEM(key *ecdsa.PrivateKey) *PEM
NewPEM creates a new PEM struct containing the PEM-encoded private and public keys for the provided ECDSA private key.
func (*PEM) Decode ¶
Decode decodes the private and public keys from PEM format. It takes the PEM-encoded private and public keys as input, and returns the corresponding ECDSA private and public keys. The function first decodes the PEM-encoded private key, then decodes the PEM-encoded public key, and returns both the private and public keys.
func (*PEM) Encode ¶
Encode encodes the provided ECDSA private and public keys into PEM format. The function returns the PEM-encoded private key and public key as strings. The private key is encoded using the "PRIVATE KEY" PEM block type, and the public key is encoded using the "PUBLIC KEY" PEM block type.
func (*PEM) GetPrivate ¶
GetPrivate returns the PEM encoded private key
type PUID ¶
type PUID struct { //UserID represents a unique user ID and is registered with the blockchain network using an OrganizationID which is optional. If the OrganizationID is not provided, the user will be registered as a personal user. UserID BigInt //OrganizationID represents a company or organization and is registered with the blockchain network by a personal users PUID OrganizationID BigInt //AppID represents a unique application ID and is registered with the blockchain network using an OrganizationID and the requesting users PUID (both are required) AppID BigInt //AssetID represents a unique asset ID and is registered with the blockchain network using a required UserID and optional OrganizationID and AppIDs. // If the OrganizationID is not provided, the asset will be registered as a personal asset and not tied to any organization or application. // If the AppID is not provided, the asset will be registered as a personal asset and not tied to any application. AssetID BigInt }
func NewPUIDEmpty ¶
func NewPUIDEmpty() *PUID
NewPUIDEmpty creates a new PUID instance with all fields set to zero. NewPUIDEmpty creates a new PUID instance with all fields set to zero.
func NewPUIDFromString ¶
NewPUIDFromString creates a new PUID instance from a string representation. The string should be in the format: "organizationID:appID:userID:assetID" and can optionally be base64-encoded.
func NewPUIDThis ¶
func NewPUIDThis() *PUID
NewPUIDThis creates a new PUID for this blockchain using the ThisBlockchain* constants
func (*PUID) GetAssetID ¶
GetAssetID returns the AssetID of the PUID.
func (*PUID) GetOrganizationID ¶
GetOrganizationID returns the OrganizationID of the PUID.
func (*PUID) IsAppID ¶
IsAppID returns true if the PUID has an AppID that matches the provided BigInt value.
func (*PUID) IsAssetID ¶
IsAssetID returns true if the PUID has an AssetID that matches the provided BigInt value.
func (*PUID) IsOrganiztionID ¶
IsOrganiztionID returns true if the PUID has an OrganizationID that matches the provided BigInt value.
func (*PUID) IsUserID ¶
IsUserID returns true if the PUID has an UserID that matches the provided BigInt value.
func (*PUID) SetAssetID ¶
SetAssetID sets the AssetID with a new AssetID of BigInt.
type Persist ¶
Persist is a transaction protocol for storing key/value pairs on the blockchain with indexing support.
type TXLookupManager ¶
type TXLookupManager struct {
// contains filtered or unexported fields
}
TXLookupManager is a struct that contains the index and methods for manipulating/searching the index to find blocks and transactions by either ID or Hash.
func NewTXLookupManager ¶
func NewTXLookupManager() *TXLookupManager
NewTXLookupManager returns a new TXLookupManager instance.
func (*TXLookupManager) Add ¶
func (txlm *TXLookupManager) Add(block *Block) error
Add adds a new entry to the index
func (*TXLookupManager) Find ¶
func (txlm *TXLookupManager) Find(indexEntry *IndexEntry) (entry *IndexEntry, err error)
Find efficiently search the index to see if thr tx hash exists and if so returns a populated IndexEntry{}
func (*TXLookupManager) Get ¶
func (txlm *TXLookupManager) Get() *Index
Get returns the index for BlockchainPersistData to save to LocalStorage
func (*TXLookupManager) Initialized ¶
func (txlm *TXLookupManager) Initialized() bool
Initialized returns true if the index has been initialized and is ready for use
func (*TXLookupManager) Set ¶
func (txlm *TXLookupManager) Set(idx *Index) error
Set sets the index from BlockchainPersistData loaded from LocalStorage
type Transaction ¶
type Transaction interface { Process() string GetProtocol() string GetID() string GetHash() string GetSignature() string GetSenderWallet() *Wallet GetFee() float64 // New method to get the transaction fee GetStatus() TransactionStatus SetStatus(status TransactionStatus) Sign(privPEM []byte) (string, error) Verify(pubKey []byte, sign string) (bool, error) Send(bc *Blockchain) error String() string Hex() string Hash() string Bytes() []byte JSON() string Validate() error Size() int EstimateFee(feePerByte float64) float64 SetPriority(priority int) GetPriority() int }
Transaction is an interface that defines the common methods for all Dynamic Protocol based transactions.
type TransactionQueryCriteria ¶
type TransactionQueryCriteria struct {
Amount float64
}
TransactionQueryCriteria represents the criteria for querying transactions.
type TransactionStatus ¶
type TransactionStatus string
TransactionStatus represents the possible states of a transaction.
const ( StatusPending TransactionStatus = "pending" StatusConfirmed TransactionStatus = "confirmed" StatusFailed TransactionStatus = "failed" )
type Tx ¶
type Tx struct { ID *PUID `json:"id"` Time time.Time `json:"time"` Version int `json:"version"` Protocol string `json:"protocol"` From *Wallet `json:"from"` To *Wallet `json:"to"` Fee float64 `json:"fee"` Status TransactionStatus `json:"status"` BlockNum int `json:"block_num"` Signature string `json:"signature"` Nonce uint64 `json:"nonce"` Data []byte `json:"data"` // contains filtered or unexported fields }
Tx is a generic transaction that represents a transfer of value between two wallets.
func NewTransaction ¶
NewTransaction creates a new transaction with the specified protocol, sender wallet, and recipient wallet.
func (*Tx) EstimateFee ¶
EstimateFee estimates the fee for the transaction based on its size and the given fee per byte.
func (*Tx) GetPriority ¶
GetPriority returns the priority of the transaction.
func (*Tx) GetProtocol ¶
GetProtocol returns the protocol ID of the transaction.
func (*Tx) GetSenderWallet ¶
GetSenderWallet retrieves the sender's wallet from the blockchain based on the sender's address.
func (*Tx) GetSignature ¶
GetSignature returns the signature of the transaction.
func (*Tx) GetStatus ¶
func (t *Tx) GetStatus() TransactionStatus
GetStatus returns the current status of the transaction.
func (*Tx) IsCoinbase ¶
IsCoinbase returns true if the transaction is a coinbase transaction.
func (*Tx) Send ¶
func (t *Tx) Send(bc *Blockchain) error
Send sends the filled and signed transaction to the network queue to be added to the blockchain.
func (*Tx) SetPriority ¶
SetPriority sets the priority of the transaction.
func (*Tx) SetStatus ¶
func (t *Tx) SetStatus(status TransactionStatus)
SetStatus sets the status of the transaction.
type Vault ¶
type Vault struct { Data map[string]interface{} // Data (keypairs) associated with the wallet Key *ecdsa.PrivateKey Pem *PEM }
Vault is a struct that holds the data (keypairs) associated with the wallet as well as the private key and PEM encoded keys
func (*Vault) GetData ¶
GetData returns the data (keypairs) associated with the wallet. This wallet allows the user to store arbitrary data (keypairs) in the wallet. The data included built-in data such as the wallet name, tags, and balance.
func (*Vault) NewKeyPair ¶
NewKeyPair creates a new keypair for the wallet
type Wallet ¶
type Wallet struct { ID *PUID Address string Encrypted bool EncryptionParams *EncryptionParams Ciphertext []byte // contains filtered or unexported fields }
Wallet represents a user's wallet. Wallets are persisted to disk as individual files. The Wallet struct contains the following fields:
ID: A unique identifier for the wallet. Address: The wallet's address. Encrypted: A flag indicating whether the private key is encrypted. EncryptionParams: The encryption parameters used to encrypt the private key. Ciphertext: The encrypted private key data. vault: A reference to the wallet's associated vault.
func NewWallet ¶
func NewWallet(options *WalletOptions) (*Wallet, error)
NewWallet creates a new wallet with a unique ID, name, and set of tags. The wallet is initialized with a new private key and default encryption parameters. The wallet must be closed to save it to disk.
func (*Wallet) Close ¶
Close encrypts and saves the wallet to disk as a JSON file. If the wallet is already encrypted, this method will return an error. This method first locks the wallet using the provided passphrase, then saves the encrypted wallet to disk using the localStorage.Set method. If any errors occur during the locking or saving process, this method will return an error.
func (*Wallet) GetAddress ¶
GetAddress generates and returns the wallet address.
If the address is already generated, it returns the cached address. Otherwise, it generates a new address by hashing the public key and encoding it in hexadecimal.
func (*Wallet) GetBalance ¶
GetBalance returns the wallet balance from the data (keypairs) associated with the wallet. If the wallet is encrypted, this function will return 0. Otherwise, it will retrieve the "balance" key from the wallet data and return it as a float64. If there is an error retrieving the balance, it will log the error and return 0.
func (*Wallet) GetData ¶
GetData returns the data (keypairs) associated with the wallet. This wallet allows the user to store arbitrary data (keypairs) in the wallet. The data included built-in data such as the wallet name, tags, and balance. If the wallet is encrypted, this method will return an error.
func (*Wallet) GetTags ¶
GetTags returns the wallet tags from the data (keypairs) associated with the wallet. If the wallet is encrypted, this function will return nil. Otherwise, it will return the tags stored in the wallet data, or nil if there is an error retrieving the tags.
func (*Wallet) GetWalletName ¶
GetWalletName returns the wallet name from the data (keypairs) associated with the wallet. If the wallet is encrypted, an empty string is returned. If there is an error retrieving the wallet name, an empty string is also returned.
func (*Wallet) Lock ¶
Lock locks the wallet using the provided passphrase. Basically the wallet's data (keypairs), including the private key are encrypted using the passphrase.
If the wallet is already encrypted, this method will return an error. If the provided passphrase is too weak, this method will also return an error.
This method first converts the passphrase to bytes, then gets the wallet's data as bytes using the vaultToBytes method. It then encrypts the wallet's data using the encrypt method and stores the ciphertext in the Ciphertext field. Finally, it sets the vault field to nil and the Encrypted field to true.
func (*Wallet) Open ¶
Open loads the wallet from disk that was saved as a JSON file. It also unlocks the value and restores the wallet.vault object.
func (*Wallet) PrivateBytes ¶
PrivateBytes returns the bytes representation of the private key associated with the wallet. If the wallet is encrypted, this method will return an error. If the private key is nil, this method will also return an error.
func (*Wallet) PrivateKey ¶
func (w *Wallet) PrivateKey() (*ecdsa.PrivateKey, error)
/ PrivateKey returns the private key from the vault associated with the wallet. / If the wallet is encrypted, this method will return an error.
func (*Wallet) PrivatePEM ¶
PrivatePEM returns the PEM representation of the private key associated with the wallet. If the wallet is encrypted, this method will return an empty string. If the private key is nil, this method will also return an empty string.
func (*Wallet) PublicBytes ¶
PublicBytes returns the bytes representation of the public key. If the wallet is encrypted, this returns an error. If the public key is nil, this returns an error. Otherwise, this returns the bytes representation of the public key.
func (*Wallet) PublicKey ¶
PublicKey returns the public key from the data (keypairs) associated with the wallet. If the wallet is encrypted, this method will return an error. If the public key is nil, this method will also return an error.
func (*Wallet) PublicPEM ¶
PublicPEM returns the PEM representation of the public key. If the wallet is encrypted, this returns an empty string. If the public key is nil, this also returns an empty string. Otherwise, it returns the PEM representation of the public key.
func (*Wallet) SendTransaction ¶
func (w *Wallet) SendTransaction(to string, tx Transaction, bc *Blockchain) (*Transaction, error)
SendTransaction sends a transaction from the wallet to the specified address on the blockchain. It first checks if the wallet is encrypted, and returns an error if it is. It then gets the wallet's balance, and checks if it has enough funds to cover the transaction fee. If the wallet has sufficient funds, it prints a log message and sends the transaction to the blockchain. If the transaction is successfully sent, it returns the transaction. If there is an error sending the transaction, it returns the error.
func (*Wallet) SetData ¶
SetData sets the data (keypairs) associated with the wallet. This method allows the user to store arbitrary data (keypairs) in the wallet. If the wallet is encrypted, this method will return an error.
func (*Wallet) Unlock ¶
Unlock unlocks the wallet using the provided passphrase. Basically the wallet's data (keypairs), including the private key are decrypted using the passphrase.
If the wallet is already decrypted, this method will return an error. If the provided passphrase is incorrect, this method will also return an error.
This method first converts the passphrase to bytes, then decrypts the wallet's data using the decrypt method. It then sets the wallet's data by calling the bytesToVault method. Finally, it sets the Ciphertext field to an empty slice and the Encrypted field to false.
type WalletOptions ¶
type WalletOptions struct { OrganizationID *BigInt AppID *BigInt UserID *BigInt AssetID *BigInt Name string Passphrase string Tags []string }
WalletOptions is a struct that contains the required options for creating a new wallet.
OrganizationID is the ID of the organization creating the wallet. AppID is the ID of the app creating the wallet. UserID is the ID of the user creating the wallet. AssetID is the ID of the asset creating the wallet. Name is the string name for the wallet. Passphrase is the passphrase for the wallet. Tags are the tags associated with the wallet.
func NewWalletOptions ¶
func NewWalletOptions(organizationID, appID, userID, assetID *BigInt, name, passphrase string, tags []string) *WalletOptions
NewWalletOptions creates a new WalletOptions struct with the provided parameters. The WalletOptions struct contains the necessary properties for creating a new wallet. The OrganizationID, AppID, UserID, and AssetID fields are pointers to BigInt values, representing the IDs of the organization, app, user, and asset associated with the wallet. The Name field is a string representing the name of the wallet. The Passphrase field is a string representing the passphrase for the wallet. The Tags field is a slice of strings representing the tags associated with the wallet.
Source Files
¶
- address.go
- api.go
- apiEndpointsAccount.go
- apikey.go
- banktx.go
- bigint.go
- block.go
- blockchain.go
- blockchaininfo.go
- coinbasetx.go
- common.go
- config.go
- const.go
- flags.go
- html5.go
- localstorage.go
- messagetx.go
- mnemonic.go
- node.go
- p2p.go
- persisttx.go
- puid.go
- sdk.go
- transaction.go
- txlookup.go
- vault.go
- wallet.go