Yu is a highly customizable blockchain framework.

Yu is a highly customizable blockchain framework.

中文文档

Overall Structure

image

Introduction

By using Yu, you can customize three levels to develop your own blockchain. The Tripod is for developers to customize their own bussiness.
First level is define Exection and Query on chain.
Second level is define blockchain lifecycle. ( including customizable Consensus Algorithm )
Third level is define basic components, such as block data structures, blockchain, blockbase, txpool.

  • Define your Exection and Query on chain.
    Execution is like Transaction in Ethereum but not only for transfer of Token, it changes the state on the chain and must be consensus on all nodes.
    Query is like query in Ethereum, it doesn't change state, just query some data from the chain.
type (
	Execution func(*context.Context, currentBlock IBlock, *chain_env.ChainEnv) error
	
	Query func(ctx *context.Context, env *chain_env.ChainEnv, blockHash common.Hash) (respObj interface{}, err error)
)
  • Define Your blockchain lifecycle, this function is in Tripod interface.
    CheckTxn defines the rules for checking transactions(Executions) before inserting txpool.
    VerifyBlock defines the rules for verifying blocks.
    InitChain defines bussiness when the blockchain starts up. You should use it to define Genesis Block.
    StartBlock defines bussiness when a new block starts. In this func, you can set some attributes( including pack txns from txpool, mining ) in the block, then you should tell the framework whether broadcast the block to other nodes or not.
    EndBlock defines bussiness when all nodes accept the new block, usually we execute the txns of new block and append block into the chain.
    FinalizeBlock defines bussiness when the block is finalized in the chain by all nodes.
type Tripod interface {

    ......
    
    CheckTxn(*txn.SignedTxn)    

    VerifyBlock(block IBlock, env *ChainEnv) bool

    InitChain(env *ChainEnv, land *Land) error

    StartBlock(block IBlock, env *ChainEnv, land *Land) (needBroadcast bool, err error)

    EndBlock(block IBlock, env *ChainEnv, land *Land) error

    FinalizeBlock(block IBlock, env *ChainEnv, land *Land) error
}

Examples

Asset Tripod
Asset Tripod imitates an Asset function, it has transfer accounts, create accounts.
QueryBalance queries someone's account balance. It implements type func Query.

func (a *Asset) QueryBalance(ctx *context.Context, env *ChainEnv, _ Hash) (interface{}, error) {
	account := ctx.GetAddress("account")
	amount := a.getBalance(env, account)
	return amount, nil
}

CreateAccount creates an account. It implements type func Execution.
EmitEvent will emit an event out of the chain.
The error returned will emit out of the chain.

func (a *Asset) CreateAccount(ctx *context.Context, _ IBlock, env *ChainEnv) error {
	addr := ctx.Caller
	amount := ctx.GetUint64("amount")

	if a.exsitAccount(env, addr) {
		_ = ctx.EmitEvent("Account Exists!")
		return nil
	}

	a.setBalance(env, addr, Amount(amount))
	_ = ctx.EmitEvent("Account Created Success!")
	return nil
}

We need use SetExec and SetQueries to set Execution and Query into Asset Tripod.
When we set a Execution, we need declare how much Lei(耜) it consumes. (Lei is the same as gas in ethereum )

func NewAsset(tokenName string) *Asset {
	df := NewDefaultTripod("asset")

	a := &Asset{df, tokenName}
	a.SetExec(a.Transfer, 100).SetExec(a.CreateAccount, 10)
	a.SetQueries(a.QueryBalance)

	return a
}

Finally set Asset Tripod into land in main func.

func main() {
    startup.StartUp(pow.NewPow(1024), asset.NewAsset("YuCoin"))
}

Pow Tripod
Pow Tripod imitates a Consensus algorithm for proof of work. It customizes the lower-level code.

  • Start a new block
    If there are no verified blocks from P2P network, we pack some txns, mine a new block and broadcast it to P2P network.
func (p *Pow) StartBlock(block IBlock, env *ChainEnv, _ *Land) (needBroadcast bool, err error) {
    ......

    // get validated blocks from P2P network, if exists, use it and return.
    pbsht, err := chain.TakeP2pBlocks(height)
    if err != nil {
   	logrus.Errorf("get p2p-blocks error: %s", err.Error())
    }
    if len(pbsht) > 0 {
   	block.CopyFrom(pbsht[0])
   	logrus.Infof("USE P2P block(%s)", block.GetHash().String())
   	env.StartBlock(block.GetHash())
   	return
    }
    
    // if there are no validated blocks from P2P network, we need to mine a block.
    needBroadcast = true

    ......

    // pack transactions(Executions) from txpool
    txns, err := pool.Pack(p.pkgTxnsLimit)
    if err != nil {
    	return
    }

    ......

    // mine a hash for the new block
    nonce, hash, err := spow.Run(block, p.target, p.targetBits)
    if err != nil {
        return
    }

    block.(*Block).SetNonce(uint64(nonce))
    block.SetHash(hash)

    ......

    return 
}
  • End the block
    We execute the txns of the block and append the block into the chain.
func (*Pow) EndBlock(block IBlock, env *ChainEnv, land *Land) error {
        ......

        // execute the txns of the block
	err := node.ExecuteTxns(block, env, land)
	if err != nil {
		return err
	}

        // append the block into chain
	err = chain.AppendBlock(block)
	if err != nil {
		return err
	}

        ......
        // flush the txpool to prepare for new txns of the next block   
        return pool.Flush()   
}
  • Finalize the block
    poW does not need finalize stage, so the FinalizeBlock has no implements.

Same as Asset Tripod , finally set Pow Tripod into land in main function.

func main() {
	startup.StartUp(pow.NewPow(1024), asset.NewAsset("YuCoin"))
}
Similar Resources

Gochain is a Blockchain written in go

Gochain is a Blockchain written in go

gochain gochain is a proof-of-work blockchain written in go. Features Proof-Of-Work Persistence CLI Transactions Addresses Merkle Tree Network How to

Jul 14, 2022

LINE Financial Blockchain forked from gaia

LFB(LINE Financial Blockchain) This repository hosts LFB(LINE Financial Blockchain). This repository is forked from gaia at 2021-03-15. LFB is a mainn

Dec 21, 2022

utreexo blockchain skeleton

utreexo blockchain skeleton

sunyata sunyata is a blockchain skeleton. It implements a minimally-functional proof-of-work blockchain, including consensus algorithms, p2p networkin

May 24, 2022

OmniFlix Hub is a blockchain built using Cosmos SDK and Tendermint and created with Starport.

OmniFlix Hub is the root chain of the OmniFlix Network. Sovereign chains and DAOs connect to the OmniFlix Hub to manage their web2 & web3 media operations (mint, manage, distribute & monetize) as well as community interactions.

Nov 10, 2022

A plugin that turn hashicorp vault into blockchain wallet.

A plugin that turn hashicorp vault into blockchain wallet.

dq-vault - Hashicorp vault BTC/ETH plugin This vault plugin stores a user's mnemonic inside vault in an encrypted manner. The plugin uses this stored

Dec 7, 2022

Tools to help teams develop smart contracts on the Cardano blockchain

Tools to help teams develop smart contracts on the Cardano blockchain

toolkit-for-cardano toolkit-for-cardano simplifies the development of Cardano smart contracts by providing teams with frequently needed tasks: Build T

Dec 19, 2022

Use golang to reproduce the basic blockchain

Blockchain_with_Go Use golang to reproduce the basic blockchain Update Panel V0.1 No transactions but noly blocks are allowed. V0.5 Transactions are n

Dec 30, 2022

Evmos is a scalable, high-throughput Proof-of-Stake blockchain that is fully compatible and interoperable with Ethereum.

Evmos Evmos is a scalable, high-throughput Proof-of-Stake blockchain that is fully compatible and interoperable with Ethereum. It's built using the Co

Dec 31, 2022

Source for the Chillis & Associates blockchain nodes

Chillis & Associates chillisd Repository This repository contains the source code for validators on the Chillis network. The source is based on the wa

Feb 8, 2022
Comments
  • IOC denpencies between tripods

    IOC denpencies between tripods

    Usually, we develop a tripod need to depend on another tripod. Right now, we could only use some inelegant codes like land.GetTripod(tripodName string) interface{}.

    The elegant way is like a spring IOC. For example:

    type ThisTripod struct {
         // auto inject  here
         other *OtherTripod
    }
    
  • Proof of Staking

    Proof of Staking

    We need proof-of-staking for yu, should develop a tripod named pos for it. This tripod has the following Writings:

    • Staking
      Callers stake their tokens on the chain. Must check if their account balance is sufficient. Then
       assets.SubBalance(caller_addr, token_amount)
       staking.State.Set(Staking, caller_addr, token_amount)
    
    • Unstaking
      Callers unstake and withdraw their tokens.

    • Delegate
    • Undelegate
  • todo-list

    todo-list

    • [x] txpool persistence
    • [x] preventing Replay Attack
    • [ ] unit tests
      • [x] txpool test
      • [x] poa test
      • [x] blockchain test
      • [x] state test
      • [ ] subscribe test
      • [ ] p2p-network test
      • [ ] kernel run test
    • [x] uncle blocks
    • [ ] benchmark
    • [ ] http api tests
    • [x] clean codes
    • [ ] vrf
    • [ ] hotstuff
    • [ ] browser
    • [ ] go-SDK
    • [ ] wallet
    • [ ] eth smart contract tests
    • [ ] multi-language template
Related tags
Blockchain-go - A repository that houses a blockchain implemented in Go

blockchain-go This is a repository that houses a blockchain implemented in Go. F

May 1, 2022
The Cosmos-SDK is a framework for building blockchain applications in Golang.
The Cosmos-SDK is a framework for building blockchain applications in Golang.

The Cosmos-SDK is a framework for building blockchain applications in Golang. It is being used to build Gaia, the first implementation of the Cosmos Hub.

Nov 26, 2021
DERO Homomorphic Encryption Blockchain Protocol
DERO Homomorphic Encryption Blockchain Protocol

Homomorphic encryption is a form of encryption allowing one to perform calculations on encrypted data without decrypting it first. The result of the computation is in an encrypted form, when decrypted the output is the same as if the operations had been performed on the unencrypted data.

Dec 27, 2022
A simplified blockchain implementation in Golang

A simplified blockchain implementation in Golang

Dec 31, 2022
DERO: Secure, Anonymous Blockchain with Smart Contracts. Subscribe to Dero announcements by sending mail to [email protected] with subject: subscribe announcements
DERO: Secure, Anonymous Blockchain with Smart Contracts.  Subscribe to Dero announcements by sending mail to lists@dero.io with subject: subscribe announcements

Welcome to the Dero Project DERO News Forum Wiki Explorer Source Twitter Discord Github Stats WebWallet Medium Table of Contents ABOUT DERO PROJECT DE

Dec 7, 2022
run ABI encoded data against the ethereum blockchain

Run EVM code against a database at a certain block height - Note You can't run this against a running geth node - because that would share the db and

Nov 11, 2021
Go module for the Cardano Blockchain

cardano-go cardano-go is both a library for creating go applicactions that interact with the Cardano Blockchain as well as a CLI to manage Cardano Wal

Dec 1, 2022
chia-blockchain some function implement in golang

gochia chia-blockchain some function implement in golang Package bls-signatures implement blspy Usage? Now we can use it to generate plot memo and id,

May 27, 2022
Frontier Chain is a blockchain application built using Cosmos SDK and Tendermint.

Frontier Chain Frontier Chain is a blockchain application built using Cosmos SDK and Tendermint. Setup Initialize the blockchain with one validator no

Jul 12, 2022
Implementing blockchain using Golang ✔️
 Implementing blockchain using Golang ✔️

Implementing blockchain using Golang ✔️ Keys The Blockchain uses ECDSA (224 bits) keys.

May 24, 2022