blockchain

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2020 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BlocksBucket       = "blocks"
	TransactionsBucket = "transactions"
	AccountsBucket     = "accounts"
	CollectionsBucket  = "collections"
	P2PPrivateKeyKey   = "p2pPrivKey"
)

Variables

This section is empty.

Functions

func DbExists

func DbExists(dbFile string) bool

func IntToHex

func IntToHex(num int64) []byte

IntToHex converts an int64 to a byte array

func IsValidAddress

func IsValidAddress(address string) bool

func IsValidSig

func IsValidSig(rawData []byte, pubKey []byte, signature []byte) bool

isValidSig verifies if the rawData is a signed correctly

func PublicKeyToAddress

func PublicKeyToAddress(publicKeyBytes []byte) (string, error)

PublicKeyToAddress generates the address of a given publicKey in bytes

func RandStringBytesMask

func RandStringBytesMask(n int) string

RandStringBytesMask generates random string using masking with source

func Sign

func Sign(privKey ecdsa.PrivateKey, rawDataDigest []byte) []byte

Sign signs the digest of rawData

func SortByteArrays added in v0.1.0

func SortByteArrays(src [][]byte) [][]byte

SortByteArrays sorts the slice of byte arrays

Types

type Account

type Account struct {
	DateOfBirth  string `json:"dateOfBirth" validate:"len=10"`
	FirstName    string `json:"firstName" validate:"nonzero"`
	LastName     string `json:"lastName" validate:"nonzero"`
	Organization string `json:"organization" validate:"nonzero"`
	Position     string `json:"position" validate:"nonzero"`
	Email        string `json:"email" validate:"min=6,max=80"`
	Phone        string `json:"phone" validate:"min=6,max=40"`
	Address      string `json:"address" validate:"min=10,max=140"`
	PublicKey    string `json:"publicKey" validate:"len=128"`
	Role         `json:"role"`
	LastModified int64 `json:"lastModified"`
}

Account represents an end user's information including the public key. Note that these account fields are just a placeholder for convenience to track identity, which doesn't affect the usage of Blocace. TODO: support ldap or other auth protocols

func DeserializeAccount

func DeserializeAccount(a []byte) *Account

DeserializeAccount deserializes an account

func UnmarshalAccount

func UnmarshalAccount(a []byte) (Account, error)

UnmarshalAccount deserializes an account for p2p

func (Account) Marshal

func (a Account) Marshal() []byte

Serialize serializes the account

func (Account) ToMap

func (a Account) ToMap(isAdmin bool) map[string]interface{}

ToMap converts an Account struct to map

type Block

type Block struct {
	Timestamp         int64
	PrevBlockHash     []byte
	Height            uint64
	Hash              []byte
	TotalTransactions int
	Transactions      []*Transaction
}

Block keeps block headers

func DeserializeBlock

func DeserializeBlock(d []byte) *Block

DeserializeBlock deserializes a block from persistence

func NewBlock

func NewBlock(transactions []*Transaction, prevBlockHash []byte, height uint64) *Block

NewBlock creates and returns Block

func NewGenesisBlock

func NewGenesisBlock(coinbase *Transaction, db *bolt.DB) *Block

NewGenesisBlock creates and returns genesis block

func (*Block) GetMerkleTree

func (b *Block) GetMerkleTree() *MerkleTree

GetMerkleTree builds a merkle tree of all the transactions in the block

func (Block) Persist

func (b Block) Persist(db *bolt.DB, isTip bool) ([]byte, error)

Persist stores the block with the transactions to DB

func (*Block) SetHash

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

SetHash set the hash of the whole block

type Blockchain

type Blockchain struct {
	Tip     []byte
	PeerId  []byte
	Db      *bolt.DB
	Search  *Search
	DataDir string
}

Blockchain keeps a sequence of Blocks. Blockchain DB keys: lastHash - l; lastHeight - b; totalTransactions - t; p2pPrivKey; peerId

func CreateBlockchain

func CreateBlockchain(dbFile string, dataDir string) *Blockchain

CreateBlockchain creates a new local blockchain DB

func NewBlockchain

func NewBlockchain(dbFile string, dataDir string) *Blockchain

NewBlockchain creates a new Blockchain with genesis Block (reading existing DB data and initializing a Blockchain struct)

func (*Blockchain) AddBlock

func (bc *Blockchain) AddBlock(txs []*Transaction) []byte

AddBlock saves provided data as a block in the blockchain

func (*Blockchain) IsComplete added in v0.1.0

func (bc *Blockchain) IsComplete() bool

IsComplete iterate all the blocks of a blockchain to check its completeness

func (*Blockchain) RegisterAccount

func (bc *Blockchain) RegisterAccount(address []byte, account Account) error

RegisterAccount persists the account to the storage

type Document

type Document struct {
	ID           string `json:"_id"`
	BlockID      string `json:"_blockId"`
	BlockchainId string `json:"_blockchainId"` // peerId
	Source       string `json:"_source"`
	Timestamp    string `json:"_timestamp"`
	Signature    string `json:"_signature"`
	Address      string `json:"_address"` // Issuer address
}

Document represents a document with metadata in the search result

type DocumentMapping

type DocumentMapping struct {
	Collection string                 `json:"collection"`
	Fields     map[string]interface{} `json:"fields"`
}

DocumentMapping represents the schema of a collection

func DeserializeDocumentMapping

func DeserializeDocumentMapping(a []byte) *DocumentMapping

DeserializeDocumentMapping deserializes encoded bytes to an DocumentMapping object

func (DocumentMapping) Serialize

func (dm DocumentMapping) Serialize() []byte

Serialize serializes the transaction

type MerkleNode

type MerkleNode struct {
	Left  *MerkleNode
	Right *MerkleNode
	Data  []byte
}

MerkleNode represents a Merkle tree node

func NewMerkleNode

func NewMerkleNode(left, right *MerkleNode, txHash []byte) *MerkleNode

NewMerkleNode creates a new Merkle tree node

type MerkleTree

type MerkleTree struct {
	RootNode *MerkleNode
}

MerkleTree represents a Merkle tree

func NewMerkleTree

func NewMerkleTree(txHashes [][]byte) *MerkleTree

NewMerkleTree creates a new Merkle tree from a sequence of data

func (MerkleTree) GetVerificationPath

func (mt MerkleTree) GetVerificationPath(txToVerify []byte) map[int][]byte

GetVerificationPath finds the necessary transaction hashes for clients to verify if a transaction has been included in the block

type Role

type Role struct {
	Name                    string   `json:"name"`
	CollectionsWrite        []string `json:"collectionsWrite"`
	CollectionsReadOverride []string `json:"collectionsReadOverride"`
}

Role represents the rights of access to collections and API endpoints

type Search struct {
	sync.Mutex

	BlockchainIndices map[string]bleve.Index
	// contains filtered or unexported fields
}

Search encapsulates all the indices with search engine features

func NewSearch

func NewSearch(db *bolt.DB, dataDir string) (*Search, error)

NewSearch create an instance to access the search features

func (*Search) CreateMapping

func (s *Search) CreateMapping(documentMapping DocumentMapping) (bleve.Index, error)

CreateMapping creates the data schema for a specific collection.

func (*Search) CreateMappingByJson

func (s *Search) CreateMappingByJson(mappingJSON []byte) (bleve.Index, error)

CreateMappingByJson creates the data schema for a specific collection, which is defined in JSON An example JSON payload:

{
    "collection": "new_collection",
    "fields": {
        "id": {"type": "text"},
        "title": {"type": "text"},
        "age": {"type": "number"},
        "created": {"type": "datetime"},
        "isModified": {"type": "boolean"},
        "location": {"type": "geopoint"}
    }
}

func (*Search) IndexBlock

func (s *Search) IndexBlock(block *Block, peerId []byte)

IndexBlock index all the txs in a block

type Transaction

type Transaction struct {
	ID                 []byte // hash
	BlockHash          []byte
	PeerId             []byte // blockchain ID
	RawData            []byte
	AcceptedTimestamp  int64
	Collection         string
	PubKey             []byte
	Signature          []byte
	PermittedAddresses []string
}

Transaction one transaction has on document

func DeserializeTransaction

func DeserializeTransaction(d []byte) *Transaction

DeserializeTransaction deserializes a transaction

func NewCoinbaseTX

func NewCoinbaseTX(peerId []byte) *Transaction

NewCoinbaseTX creates a new coinbase transaction

func NewTransaction

func NewTransaction(peerId []byte, data []byte, collection string, pubKey []byte, signature []byte, permittedAddresses []string) *Transaction

NewTransaction creates a new transaction

func (*Transaction) Serialize

func (tx *Transaction) Serialize() []byte

Serialize serializes the transaction

func (*Transaction) SetID

func (tx *Transaction) SetID()

SetID sets ID of a transaction based on the raw data and timestamp

Jump to

Keyboard shortcuts

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