sdk

package
v0.0.0-...-49f4f44 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2024 License: Apache-2.0 Imports: 46 Imported by: 0

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

View Source
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
)
View Source
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"
)
View Source
const (
	PersistProtocolID  = "PERSIST"
	BankProtocolID     = "BANK"
	MessageProtocolID  = "MESSAGE"
	CoinbaseProtocolID = "COINBASE"
	ChainProtocolID    = "CHAIN"
)

Protocol IDs

View Source
const TransactionVersion = 1

TransactionVersion represents the current version of the transaction structure.

Variables

View Source
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)
)

AvailableProtocols is a list of all available protocols

View Source
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

func ConvertToFloat64(value interface{}) (float64, error)

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

func DeriveKeyPair(mnemonic string, password string) (publicKey, privateKey []byte, err error)

DeriveKeyPair derives a public/private key pair from a given mnemonic passphrase.

func GenerateMnemonic

func GenerateMnemonic() (string, error)

GenerateMnemonic generates a new 12-word mnemonic passphrase.

func GenerateRandomPassword

func GenerateRandomPassword() (string, error)

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

func GenerateWalletAddress(publicKey []byte) (string, error)

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

func GetUserIP(r *http.Request) string

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

func IntToBytes(n int) []byte

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

func LocalWalletCount() (count int, err error)

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 Name

func Name() string

Name returns the name of the SDK

func NewLocalStorage

func NewLocalStorage(dataPath string) error

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 SecureRandomInt(max int) int

func SendGmail

func SendGmail(to, subject, body string, cfg *Config) error

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

func ValidateAddress(address string) error

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

func VerifySignature(message []byte, signature []byte, publicKey *ecdsa.PublicKey) bool

VerifySignature verifies the provided signature against the given message and public key. It returns true if the signature is valid, and false otherwise.

func Version

func Version() string

Version returns the version of the SDK

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API is the blockchain API.

func NewAPI

func NewAPI(bc *Blockchain) *API

NewAPI creates a new instance of the blockchain API.

func (*API) GetConfig

func (api *API) GetConfig() *Config

func (*API) IsRunning

func (api *API) IsRunning() bool

IsRunning returns true if the API is running

func (*API) Start

func (api *API) Start()

Start starts the API and listens for incoming requests

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

type APIKeyList map[string]string

APIKeyList is a map of API keys to their corresponding values. This type is used to store and manage API keys.

type Address

type Address struct {
	RawAddress       string
	PrependedAddress string
}

Address represents a blockchain address. It contains the raw address string and a prepended version of the address.

func NewAddress

func NewAddress(rawAddress, blockchainSymbol string) *Address

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

func (a *Address) GetAddressHash() string

GetAddressHash calculates and returns the SHA-256 hash of the prepended address.

func (*Address) GetPrependedAddress

func (a *Address) GetPrependedAddress() string

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

func (a *Address) GetRawAddress() string

GetRawAddress returns the raw address string of the Address.

type Arguments

type Arguments struct {
	Flags map[string]*Flag
}

Arguments handles parsing arguments and displaying usage information

var (
	// ErrNoArgs is returned when the program is started with no arguments
	ErrNoArgs = errors.New("no arguments")

	// Args is the global Arguments instance
	Args *Arguments
)

func NewArguments

func NewArguments() *Arguments

NewArguments creates a new Arguments instance

func (*Arguments) GetBool

func (a *Arguments) GetBool(name string) bool

GetBool returns the boolean value of the named flag

func (*Arguments) GetFloat64

func (a *Arguments) GetFloat64(name string) float64

GetFloat64 returns the float64 value of the named flag

func (*Arguments) GetInt

func (a *Arguments) GetInt(name string) int

GetInt returns the int value of the named flag

func (*Arguments) GetInt64

func (a *Arguments) GetInt64(name string) int64

GetInt64 returns the int64 value of the named flag

func (*Arguments) GetString

func (a *Arguments) GetString(name string) string

GetString returns the string value of the named flag

func (*Arguments) Parse

func (a *Arguments) Parse() error

func (*Arguments) PrintUsage

func (a *Arguments) PrintUsage()

PrintUsage prints usage information for all registered arguments

func (*Arguments) Register

func (a *Arguments) Register(name string, desc string, defaultVal interface{})

Register registers a new flag

type Bank

type Bank struct {
	Tx
	Amount float64
}

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

func NewBankTransaction(from *Wallet, to *Wallet, amount float64) (*Bank, error)

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

func (b *Bank) Process() string

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 NewBigInt

func NewBigInt(val int64) *BigInt

NewBigInt creates a new BigInt instance.

func NewBigIntFromBytes

func NewBigIntFromBytes(bytes []byte) *BigInt

NewBigIntFromBytes creates a new BigInt instance from a byte slice.

func NewBigIntFromString

func NewBigIntFromString(s string) (*BigInt, error)

NewBigIntFromString creates a new BigInt instance from a string representation. If the input string is base64-encoded, it will be decoded first.

func NewRandomBigInt

func NewRandomBigInt() (*BigInt, error)

NewRandomBigInt creates a new BigInt instance with a random value.

func (*BigInt) Abs

func (b *BigInt) Abs() *BigInt

Abs returns the absolute value of the BigInt.

func (*BigInt) Add

func (b *BigInt) Add(other *BigInt) *BigInt

Add adds the given BigInt to the current BigInt.

func (*BigInt) And

func (b *BigInt) And(other *BigInt) *BigInt

Bitwise AND operation

func (*BigInt) Base64

func (b *BigInt) Base64() string

Base64 returns the base64 representation of the BigInt.

func (*BigInt) Bytes

func (b *BigInt) Bytes() []byte

Bytes returns the byte representation of the BigInt.

func (*BigInt) Compare

func (b *BigInt) Compare(other *BigInt) int

Compare compares the current BigInt with the given BigInt.

func (*BigInt) Divide

func (b *BigInt) Divide(other *BigInt) *BigInt

Divide divides the current BigInt by the given BigInt.

func (*BigInt) IsEqual

func (b *BigInt) IsEqual(other *BigInt) bool

IsEqual returns true if the current BigInt is equal to the given BigInt.

func (*BigInt) IsGreaterThan

func (b *BigInt) IsGreaterThan(other *BigInt) bool

IsGreaterThan returns true if the current BigInt is greater than the given BigInt.

func (*BigInt) IsLessThan

func (b *BigInt) IsLessThan(other *BigInt) bool

IsLessThan returns true if the current BigInt is less than the given BigInt.

func (*BigInt) IsNegative

func (b *BigInt) IsNegative() bool

IsNegative returns true if the BigInt is negative.

func (*BigInt) IsPositive

func (b *BigInt) IsPositive() bool

IsPositive returns true if the BigInt is positive.

func (*BigInt) IsZero

func (b *BigInt) IsZero() bool

IsZero returns true if the BigInt is zero.

func (*BigInt) Modulo

func (b *BigInt) Modulo(other *BigInt) *BigInt

Modulo returns the modulo of the current BigInt by the given BigInt.

func (*BigInt) Multiply

func (b *BigInt) Multiply(other *BigInt) *BigInt

Multiply multiplies the given BigInt with the current BigInt.

func (*BigInt) Neg

func (b *BigInt) Neg() *BigInt

Neg returns the negation of the BigInt.

func (*BigInt) Not

func (b *BigInt) Not() *BigInt

Not returns the bitwise complement of the BigInt.

func (*BigInt) Or

func (b *BigInt) Or(other *BigInt) *BigInt

Bitwise OR operation

func (*BigInt) Random

func (b *BigInt) Random() (*BigInt, error)

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) Shl

func (b *BigInt) Shl(n uint) *BigInt

Shl shifts the BigInt left by the given number of bits.

func (*BigInt) Shr

func (b *BigInt) Shr(n uint) *BigInt

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.

func (*BigInt) String

func (b *BigInt) String() string

String returns the string representation of the BigInt.

func (*BigInt) Subtract

func (b *BigInt) Subtract(other *BigInt) *BigInt

Subtract subtracts the given BigInt from the current BigInt.

func (*BigInt) Xor

func (b *BigInt) Xor(other *BigInt) *BigInt

Bitwise XOR operation

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

func DeserializeBlock(d []byte) (*Block, error)

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

func (b *Block) AdjustDifficulty(previousBlock *Block, targetBlockTime time.Duration) uint32

AdjustDifficulty adjusts the mining difficulty based on the time taken to mine recent blocks.

func (*Block) Bytes

func (b *Block) Bytes() []byte

Bytes returns the serialized byte representation of the block.

func (*Block) CalculateBlockReward

func (b *Block) CalculateBlockReward(currentBlockHeight int64) float64

CalculateBlockReward calculates the block reward based on the current block height.

func (*Block) CalculateHash

func (b *Block) CalculateHash() string

CalculateHash calculates and returns the hash of the block.

func (*Block) CalculateMerkleRoot

func (b *Block) CalculateMerkleRoot() []byte

CalculateMerkleRoot calculates the Merkle root of the block's transactions.

func (*Block) CalculateTotalFees

func (b *Block) CalculateTotalFees() float64

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.

func (*Block) Mine

func (b *Block) Mine(difficulty uint)

Mine performs the proof-of-work algorithm to mine the block.

func (*Block) Serialize

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

Serialize serializes the block into a byte slice.

func (*Block) String

func (b *Block) String() string

String returns a string representation of the block.

func (*Block) Validate

func (b *Block) Validate(previousBlock *Block) error

Validate checks if the block is valid.

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

type BlockchainData struct {
	ID      string
	Version string
}

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

func NewCoinbaseTransaction(from *Wallet, to *Wallet, cfg *Config) (*Coinbase, error)

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.

func (*Coinbase) Process

func (c *Coinbase) Process() string

Process updates the wallet balance with the token count and returns a string describing the transfer of the transaction fee.

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) Path

func (c *Config) Path() string

Path returns the path to the executable file.

func (*Config) PromptWalletInfo

func (c *Config) PromptWalletInfo() (walletName string, walletPass string, walletTags []string)

PromptWalletInfo prompts the user to enter wallet information.

func (*Config) PromptYesNo

func (c *Config) PromptYesNo(question string) bool

PromptYesNo prompts the user with a given question and returns a bool value based on their response.

func (*Config) Show

func (c *Config) Show()

Show displays the configuration values.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

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

func NewFIFOQueue(capacity int) *FIFOQueue

NewFIFOQueue creates a new FIFO queue with the specified capacity.

func (*FIFOQueue) Dequeue

func (q *FIFOQueue) Dequeue() string

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

func (q *FIFOQueue) Enqueue(element string)

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) Exists

func (q *FIFOQueue) Exists(entry string) bool

Exists tells whether the Index contains entry.

func (*FIFOQueue) Find

func (q *FIFOQueue) Find(s string) string

Find returns the first entry in the Index that contains the string s, or an empty string if no match is found.

func (*FIFOQueue) Get

func (q *FIFOQueue) Get() *Index

Get returns the entire Index.

func (*FIFOQueue) IsEmpty

func (q *FIFOQueue) IsEmpty() bool

IsEmpty checks if the queue is empty.

func (*FIFOQueue) Len

func (q *FIFOQueue) Len() int

Len returns the current number of elements in the queue.

func (*FIFOQueue) Set

func (q *FIFOQueue) Set(index *Index)

Set sets the entire Index.

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

func (*Flag) Bool

func (f *Flag) Bool(name string, value bool, usage string) *bool

func (*Flag) Float64

func (f *Flag) Float64(name string, value float64, usage string) *float64

func (*Flag) Int

func (f *Flag) Int(name string, value int, usage string) *int

func (*Flag) Int64

func (f *Flag) Int64(name string, value int64, usage string) *int64

func (*Flag) String

func (f *Flag) String(name string, value string, usage string) *string

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

func (h *HTML5) RenderFormLogin() string

RenderFormLogin returns string content representing a valid HTML5 login form

func (*HTML5) RenderPage

func (h *HTML5) RenderPage(title, content string) string

RenderPage returns string content representing a valid HTML5 page

func (*HTML5) RenderPageHeader

func (h *HTML5) RenderPageHeader() string

RenderPageHeader returns string content representing a valid HTML5 page header

func (*HTML5) RenderPageLogin

func (h *HTML5) RenderPageLogin() string

RenderPageLogin returns string content representing a valid HTML5 page with the login form centered on the page

func (*HTML5) RenderPageNotImplemented

func (h *HTML5) RenderPageNotImplemented(name string) string

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

type IndexEntry struct {
	BlockNumber big.Int
	TxID        string
	TxHash      string
}

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

type Message struct {
	Tx
	Message string
}

Message is a transaction that represents a message sent from one user to another.

func NewMessageTransaction

func NewMessageTransaction(from *Wallet, to *Wallet, message string) (*Message, error)

NewMessageTransaction creates a new message transaction.

func (*Message) Process

func (m *Message) Process() string

Process returns a string representation of the message.

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 GetNode

func GetNode() *Node

func (*Node) IsReady

func (n *Node) IsReady() bool

IsReady returns true if the node is ready for use.

func (*Node) ProcessP2PTransaction

func (n *Node) ProcessP2PTransaction(tx P2PTransaction) error

ProcessP2PTransaction processes a P2PTransaction received from the P2P network.

func (*Node) Register

func (n *Node) Register() error

Register registers the node with the P2P network.

func (*Node) Run

func (n *Node) Run()

Run runs the node.

type NodeData

type NodeData struct {
	ID   string
	Name string
}

NodeData represents a node in the system, with an ID and a Name.

type NodeInfo

type NodeInfo struct {
	ID      string `json:"id"`
	Address string `json:"address"`
}

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

type NodePersistData struct {
	ID     string
	Config *Config
}

NodePersistData is the data that is persisted for a node to disk.

type NodeStatus

type NodeStatus struct {
	NodeID string `json:"node_id"`
	Status string `json:"status"`
}

type P2P

type P2P struct {
	// contains filtered or unexported fields
}

P2P represents the P2P network.

func NewP2P

func NewP2P() *P2P

NewP2P creates a new 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) BroadcastStatus

func (p *P2P) BroadcastStatus(node *Node, status string) error

func (*P2P) ConnectToSeedNode

func (p *P2P) ConnectToSeedNode(address string) error

func (*P2P) HasTransaction

func (p *P2P) HasTransaction(id *PUID) bool

HasTransaction checks if the P2P network has a specified transaction.

func (*P2P) IsRegistered

func (p *P2P) IsRegistered(nodeID string) bool

IsRegistered returns true if the given node is registered with the P2P network.

func (*P2P) IsRunning

func (p *P2P) IsRunning() bool

IsRunning returns true if the P2P network is running

func (*P2P) ProcessQueue

func (p *P2P) ProcessQueue()

ProcessQueue processes the pending transactions in the queue.

func (*P2P) RegisterNode

func (p *P2P) RegisterNode(node *Node) error

RegisterNode registers a new node with the P2P network.

func (*P2P) SetAsSeedNode

func (p *P2P) SetAsSeedNode()

func (*P2P) Start

func (p *P2P) Start() error

Start starts the P2P network

func (*P2P) Stop

func (p *P2P) Stop() error

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

type PEM struct {
	PrivateKey string
	PublicKey  string
}

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) AsBytes

func (p *PEM) AsBytes(s string) []byte

AsBytes returns the PEM encoded keys as bytes

func (*PEM) Decode

func (p *PEM) Decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey)

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

func (p *PEM) Encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string)

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

func (p *PEM) GetPrivate() string

GetPrivate returns the PEM encoded private key

func (*PEM) GetPublic

func (p *PEM) GetPublic() string

GetPublic returns the PEM encoded public 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 NewPUID

func NewPUID(organizationID, appID, userID, assetID *BigInt) *PUID

NewPUID creates a new PUID instance.

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

func NewPUIDFromString(puidStr string) (*PUID, error)

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) Base64

func (p *PUID) Base64() string

Base64 returns the base64 representation of the PUID.

func (*PUID) Bytes

func (p *PUID) Bytes() []byte

Bytes returns the byte representation of the PUID.

func (*PUID) Equal

func (p *PUID) Equal(other *PUID) bool

Equal returns true if the given PUID is equal to the current PUID.

func (*PUID) GetAppID

func (p *PUID) GetAppID() *BigInt

GetAppID returns the AppID of the PUID.

func (*PUID) GetAssetID

func (p *PUID) GetAssetID() *BigInt

GetAssetID returns the AssetID of the PUID.

func (*PUID) GetOrganizationID

func (p *PUID) GetOrganizationID() *BigInt

GetOrganizationID returns the OrganizationID of the PUID.

func (*PUID) GetUserID

func (p *PUID) GetUserID() *BigInt

GetUserID returns the UserID of the PUID.

func (*PUID) IsAppID

func (p *PUID) IsAppID(appID *BigInt) bool

IsAppID returns true if the PUID has an AppID that matches the provided BigInt value.

func (*PUID) IsAssetID

func (p *PUID) IsAssetID(assetID *BigInt) bool

IsAssetID returns true if the PUID has an AssetID that matches the provided BigInt value.

func (*PUID) IsOrganiztionID

func (p *PUID) IsOrganiztionID(organizationID *BigInt) bool

IsOrganiztionID returns true if the PUID has an OrganizationID that matches the provided BigInt value.

func (*PUID) IsUserID

func (p *PUID) IsUserID(userID *BigInt) bool

IsUserID returns true if the PUID has an UserID that matches the provided BigInt value.

func (*PUID) IsZero

func (p *PUID) IsZero() bool

IsZero returns true if the PUID is zero (all fields are zero).

func (*PUID) SetAssetID

func (p *PUID) SetAssetID(assetID *BigInt)

SetAssetID sets the AssetID with a new AssetID of BigInt.

func (*PUID) String

func (p *PUID) String() string

String returns the string representation of the PUID.

type Persist

type Persist struct {
	Tx
	Data map[string]string // Key/value pairs to be stored
}

Persist is a transaction protocol for storing key/value pairs on the blockchain with indexing support.

func NewPersistTransaction

func NewPersistTransaction(from *Wallet, to *Wallet, fee float64, data map[string]string) (*Persist, error)

NewPersistTransaction creates a new Persist transaction.

func (*Persist) Process

func (p *Persist) Process() string

Process processes the Persist transaction.

type State

type State struct {
}

State represents the current state of the blockchain.

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

func NewTransaction(protocol string, from *Wallet, to *Wallet) (*Tx, error)

NewTransaction creates a new transaction with the specified protocol, sender wallet, and recipient wallet.

func (*Tx) Bytes

func (t *Tx) Bytes() []byte

Bytes returns the serialized byte representation of the transaction.

func (*Tx) EstimateFee

func (t *Tx) EstimateFee(feePerByte float64) float64

EstimateFee estimates the fee for the transaction based on its size and the given fee per byte.

func (*Tx) GetFee

func (t *Tx) GetFee() float64

GetFee returns the fee for the transaction.

func (*Tx) GetHash

func (t *Tx) GetHash() string

GetHash returns the hash of the transaction.

func (*Tx) GetID

func (t *Tx) GetID() string

GetID returns the ID of the transaction.

func (*Tx) GetPriority

func (t *Tx) GetPriority() int

GetPriority returns the priority of the transaction.

func (*Tx) GetProtocol

func (t *Tx) GetProtocol() string

GetProtocol returns the protocol ID of the transaction.

func (*Tx) GetSenderWallet

func (t *Tx) GetSenderWallet() *Wallet

GetSenderWallet retrieves the sender's wallet from the blockchain based on the sender's address.

func (*Tx) GetSignature

func (t *Tx) GetSignature() string

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) Hash

func (t *Tx) Hash() string

Hash returns the hash of the transaction as a string.

func (*Tx) Hex

func (t *Tx) Hex() string

Hex returns the hexadecimal representation of the transaction.

func (*Tx) IsCoinbase

func (t *Tx) IsCoinbase() bool

IsCoinbase returns true if the transaction is a coinbase transaction.

func (*Tx) JSON

func (t *Tx) JSON() string

JSON returns the JSON representation of the transaction as a string.

func (*Tx) Log

func (t *Tx) Log() string

Log returns a string with the log of the transaction.

func (*Tx) Process

func (t *Tx) Process() string

Process returns a string with the process of the 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

func (t *Tx) SetPriority(priority int)

SetPriority sets the priority of the transaction.

func (*Tx) SetStatus

func (t *Tx) SetStatus(status TransactionStatus)

SetStatus sets the status of the transaction.

func (*Tx) Sign

func (t *Tx) Sign(privPEM []byte) (string, error)

Sign signs the transaction with the provided private key.

func (*Tx) Size

func (t *Tx) Size() int

Size returns the size of the transaction in bytes.

func (*Tx) String

func (t *Tx) String() string

String returns a string representation of the transaction.

func (*Tx) Validate

func (t *Tx) Validate() error

Validate checks if the transaction is valid.

func (*Tx) Verify

func (t *Tx) Verify(pubKey []byte, sign string) (bool, error)

Verify verifies the signature of the transaction with the provided public key.

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 NewVault

func NewVault() *Vault

NewVault creates a new Vault struct

func NewVaultWithData

func NewVaultWithData(name string, tags []string, balance float64) *Vault

func (*Vault) GetData

func (v *Vault) GetData(key string) (interface{}, error)

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

func (v *Vault) NewKeyPair() (err error)

NewKeyPair creates a new keypair for the wallet

func (*Vault) PrivatePEM

func (v *Vault) PrivatePEM() string

PrivatePEM returns the private key

func (*Vault) PublicPEM

func (v *Vault) PublicPEM() string

PublicPEM returns the public key

func (*Vault) SetData

func (v *Vault) SetData(key string, value interface{}) error

SetData sets 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.

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

func (w *Wallet) Close(passphrase string) error

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

func (w *Wallet) GetAddress() string

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

func (w *Wallet) GetBalance() float64

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

func (w *Wallet) GetData(key string) (interface{}, error)

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

func (w *Wallet) GetTags() []string

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

func (w *Wallet) GetWalletName() string

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

func (w *Wallet) Lock(passphrase string) error

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

func (w *Wallet) Open(passphrase string) error

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

func (w *Wallet) PrivateBytes() ([]byte, error)

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

func (w *Wallet) PrivatePEM() string

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

func (w *Wallet) PublicBytes() ([]byte, error)

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

func (w *Wallet) PublicKey() (*ecdsa.PublicKey, error)

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

func (w *Wallet) PublicPEM() string

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

func (w *Wallet) SetData(key string, value interface{}) error

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

func (w *Wallet) Unlock(passphrase string) error

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.

Jump to

Keyboard shortcuts

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