Top Related Projects
Stellar's public monorepo of go code
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Go implementation of the Ethereum protocol
⟁ Tendermint Core (BFT Consensus) in Go
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Quick Overview
Go-algorand is the official implementation of the Algorand blockchain protocol, written in Go. It provides the core functionality for running Algorand nodes, participating in consensus, and interacting with the Algorand network. This repository contains the source code for the Algorand node software and related tools.
Pros
- High performance and scalability due to its Pure Proof-of-Stake consensus mechanism
- Strong security features and cryptographic foundations
- Active development and regular updates from the Algorand team
- Comprehensive documentation and developer resources
Cons
- Relatively complex codebase for newcomers to blockchain development
- Limited ecosystem compared to some more established blockchain platforms
- Requires significant computational resources to run a full node
- Steep learning curve for understanding the intricacies of the Algorand protocol
Code Examples
- Creating a new account:
account := crypto.GenerateAccount()
address := account.Address.String()
privateKey := account.PrivateKey
- Connecting to an Algorand node:
algodClient, err := algod.MakeClient(algodAddress, algodToken)
if err != nil {
log.Fatal("Failed to create algod client:", err)
}
- Sending a transaction:
txParams, err := algodClient.SuggestedParams().Do(context.Background())
if err != nil {
log.Fatal("Error getting suggested params:", err)
}
tx, err := transaction.MakePaymentTxn(sender, receiver, amount, note, closeRemainderTo, txParams)
if err != nil {
log.Fatal("Error creating transaction:", err)
}
signedTx, err := tx.Sign(senderPrivateKey)
if err != nil {
log.Fatal("Error signing transaction:", err)
}
txID, err := algodClient.SendRawTransaction(signedTx).Do(context.Background())
if err != nil {
log.Fatal("Error sending transaction:", err)
}
Getting Started
To get started with go-algorand:
-
Clone the repository:
git clone https://github.com/algorand/go-algorand.git
-
Install dependencies:
cd go-algorand ./scripts/install_deps.sh
-
Build the project:
make build
-
Run a node:
./goal node start
For more detailed instructions and configuration options, refer to the official Algorand documentation.
Competitor Comparisons
Stellar's public monorepo of go code
Pros of Stellar
- More extensive documentation and examples
- Larger community and ecosystem
- Better support for cross-border payments and asset issuance
Cons of Stellar
- Less focus on smart contracts compared to Algorand
- Lower theoretical transaction throughput
- More complex consensus mechanism
Code Comparison
Stellar (transaction creation):
tx, err := txnbuild.NewTransaction(
txnbuild.TransactionParams{
SourceAccount: &sourceAccount,
IncrementSequenceNum: true,
Operations: []txnbuild.Operation{&payment},
BaseFee: txnbuild.MinBaseFee,
Timebounds: txnbuild.NewTimeout(300),
},
)
Algorand (transaction creation):
tx, err := future.MakePaymentTxn(from, to, amount, note, closeRemainderTo, genesisID, genesisHash)
if err != nil {
return
}
Both repositories provide Go implementations for their respective blockchain platforms. Stellar focuses on creating a global payment network, while Algorand emphasizes scalability and security. Stellar's codebase is more mature and has a larger ecosystem, but Algorand offers more advanced smart contract capabilities and a simpler consensus mechanism. The code examples show that Stellar's transaction creation is more verbose, while Algorand's is more concise.
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Pros of Cosmos SDK
- More flexible and customizable for building application-specific blockchains
- Larger ecosystem with multiple interconnected chains (Cosmos Hub, Osmosis, etc.)
- Stronger focus on interoperability between different blockchains
Cons of Cosmos SDK
- Higher complexity and steeper learning curve for developers
- Potentially slower transaction finality compared to Algorand's pure proof-of-stake
- Less emphasis on layer-1 scalability, relying more on application-specific chains
Code Comparison
Cosmos SDK (Go):
func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
Go-Algorand:
func (l *Ledger) InitState(genesisInitState InitState) error {
l.trackerMu.Lock()
defer l.trackerMu.Unlock()
l.genesisHash = genesisInitState.GenesisHash
l.genesisProto = genesisInitState.GenesisProto
return l.accts.initAccounts(genesisInitState.Accounts)
}
The code snippets show different approaches to chain initialization, with Cosmos SDK using a modular approach and Go-Algorand focusing on ledger-specific initialization.
Go implementation of the Ethereum protocol
Pros of go-ethereum
- Larger and more established community, with extensive documentation and resources
- Supports smart contracts with Turing-complete functionality
- More widely adopted and battle-tested in production environments
Cons of go-ethereum
- Higher transaction fees and slower transaction finality compared to Algorand
- More complex consensus mechanism (Proof of Work transitioning to Proof of Stake)
- Higher energy consumption due to its current Proof of Work consensus
Code Comparison
go-ethereum (Ethereum):
func (s *Ethereum) Start() error {
if err := s.startEthService(); err != nil {
return err
}
return nil
}
go-algorand (Algorand):
func (node *AlgorandFullNode) Start() error {
node.mu.Lock()
defer node.mu.Unlock()
if node.running {
return fmt.Errorf("node already running")
}
node.running = true
return nil
}
Both repositories implement a Start()
function for their respective nodes, but go-algorand includes additional checks for the node's running state and uses a mutex for thread safety.
⟁ Tendermint Core (BFT Consensus) in Go
Pros of Tendermint
- More flexible and modular architecture, allowing for easier customization
- Broader ecosystem support and integration with various blockchain frameworks
- More mature project with longer development history and wider adoption
Cons of Tendermint
- Higher complexity due to its modular design, potentially steeper learning curve
- May require more configuration and setup compared to Go-Algorand's streamlined approach
- Potentially lower performance in certain scenarios due to its consensus mechanism
Code Comparison
Tendermint (consensus voting):
func (cs *State) signVote(type_ tmproto.SignedMsgType, hash []byte, header tmproto.PartSetHeader) (*types.Vote, error) {
addr := cs.privValidator.GetPubKey().Address()
valIdx, _ := cs.Validators.GetByAddress(addr)
vote := &types.Vote{
ValidatorAddress: addr,
ValidatorIndex: valIdx,
Height: cs.Height,
Round: cs.Round,
Timestamp: cs.voteTime(),
Type: type_,
BlockID: types.BlockID{Hash: hash, PartSetHeader: header},
}
err := cs.privValidator.SignVote(cs.state.ChainID, vote)
return vote, err
}
Go-Algorand (block proposal):
func (p *player) proposalForBlock(ve *ledger.ValidatedBlock) (proposal proposalValue, err error) {
proposal = proposalValue{
Original: ve,
Digest: ve.Digest(),
}
proposal.EncodingDigest = crypto.HashObj(proposal)
return
}
These code snippets showcase different approaches to consensus mechanisms and block proposals in the two projects.
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Pros of Fabric
- More mature and widely adopted in enterprise environments
- Flexible architecture supporting multiple consensus mechanisms
- Rich ecosystem with extensive documentation and tooling
Cons of Fabric
- Higher complexity and steeper learning curve
- Potentially slower transaction finality compared to Algorand
- More resource-intensive to set up and maintain
Code Comparison
Fabric (Chaincode in Go):
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, id string, value int) error {
asset := Asset{ID: id, Value: value}
assetJSON, err := json.Marshal(asset)
if err != nil {
return err
}
return ctx.GetStub().PutState(id, assetJSON)
}
Algorand (Smart Contract in PyTeal):
def approval_program():
on_creation = Seq([
App.globalPut(Bytes("Creator"), Txn.sender()),
Return(Int(1))
])
program = Cond(
[Txn.application_id() == Int(0), on_creation],
[Txn.on_completion() == OnComplete.OptIn, Return(Int(1))],
[Txn.on_completion() == OnComplete.CloseOut, Return(Int(1))]
)
return program
Both repositories offer robust blockchain solutions, but Fabric is more suited for complex enterprise applications, while Algorand focuses on high performance and simplicity.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
go-algorand
Branch | Build Status |
---|---|
rel/stable | |
rel/beta | |
rel/nightly |
Algorand's official implementation in Go.
Algorand is a permissionless, pure proof-of-stake blockchain that delivers decentralization, scalability, security, and transaction finality.
Getting Started
Visit our developer website for the most up-to-date information about using and installing the Algorand platform.
Building from Source
Development is done using the Go Programming Language. The Go version is specified in the project's go.mod file. This document assumes you have a functioning environment set up. If you need assistance setting up an environment, please visit the official Go documentation website.
Linux / OSX
We currently strive to support Debian-based distributions, with Ubuntu 20.04 as our official release target. Building on Arch Linux also works well. Our core engineering team uses Linux and OSX, so both environments are well-supported for development.
OSX Only: Homebrew (brew) must be installed before continuing. Here are the installation requirements.
Initial Environment Setup
git clone https://github.com/algorand/go-algorand
cd go-algorand
./scripts/configure_dev.sh
./scripts/buildtools/install_buildtools.sh
At this point, you are ready to build go-algorand. We use make
and have several targets to automate common tasks.
Build
make install
Test
# Unit tests
make test
# Integration tests
make integration
Style and Checks
make fmt
make lint
make fix
make vet
Alternatively, run:
make sanity
Running a Node
Once the software is built, you'll find binaries in ${GOPATH}/bin
, and a data directory will be initialized at ~/.algorand
. Start your node with:
${GOPATH}/bin/goal node start -d ~/.algorand
Use:
${GOPATH}/bin/carpenter -d ~/.algorand
to see activity. Refer to the developer website for instructions on using different tools.
Providing Your Own Data Directory
You can run a node out of other directories than ~/.algorand
and join networks other than mainnet. Just make a new directory and copy the genesis.json
file for the network into it. For example:
mkdir ~/testnet_data
cp installer/genesis/testnet/genesis.json ~/testnet_data/genesis.json
${GOPATH}/bin/goal node start -d ~/testnet_data
Genesis files for mainnet, testnet, and betanet can be found in installer/genesis/
.
Contributing
Please refer to our CONTRIBUTING document.
Project Layout
go-algorand
is organized into various subsystems and packages:
Core
Provides core functionality to the algod
and kmd
daemons, as well as other tools and commands:
- crypto: Contains the cryptographic constructions used for hashing, signatures, and VRFs. It also includes Algorand-specific details about spending keys, protocol keys, one-time-use signing keys, and how they relate to each other.
- config: Holds configuration parameters, including those used locally by the node and those that must be agreed upon by the protocol.
- data: Defines various types used throughout the codebase.
- basics: Holds basic types such as MicroAlgos, account data, and addresses.
- account: Defines accounts, including "root" accounts (which can spend money) and "participation" accounts (which can participate in the agreement protocol).
- transactions: Defines transactions that accounts can issue against the Algorand state, including standard payments and participation key registration transactions.
- bookkeeping: Defines blocks, which are batches of transactions atomically committed to Algorand.
- pools: Implements the transaction pool, holding transactions seen by a node in memory before they are proposed in a block.
- committee: Implements the credentials that authenticate a participating account's membership in the agreement protocol.
- ledger (README): Contains the Algorand Ledger state machine, which holds the sequence of blocks. The Ledger executes the state transitions resulting from applying these blocks. It answers queries on blocks (e.g., what transactions were in the last committed block?) and on accounts (e.g., what is my balance?).
- protocol: Declares constants used to identify protocol versions, tags for routing network messages, and prefixes for domain separation of cryptographic inputs. It also implements the canonical encoder.
- network: Contains the code for participating in a mesh network based on WebSockets. It maintains connections to some number of peers, (optionally) accepts connections from peers, sends point-to-point and broadcast messages, and receives messages, routing them to various handler code (e.g., agreement/gossip/network.go registers three handlers).
- rpcs: Contains the HTTP RPCs used by
algod
processes to query one another.
- rpcs: Contains the HTTP RPCs used by
- agreement (README): Contains the agreement service, which implements Algorand's Byzantine Agreement protocol. This protocol allows participating accounts to quickly confirm blocks in a fork-safe manner, provided that sufficient account stake is correctly executing the protocol.
- node: Integrates the components above and handles initialization and shutdown. It provides queries into these components.
Daemon
Contains the two daemons that provide Algorand clients with services:
- daemon/algod: Holds the
algod
daemon, which implements a participating node.algod
allows a node to participate in the agreement protocol, submit and confirm transactions, and view the state of the Algorand Ledger.- daemon/algod/api (README): The REST interface used for interactions with
algod
.
- daemon/algod/api (README): The REST interface used for interactions with
- daemon/kmd (README): Holds the
kmd
daemon, which allows a node to sign transactions. Sincekmd
is separate fromalgod
, it enables a user to sign transactions on an air-gapped computer.
Interfacing
Enables developers to interface with the Algorand system:
- cmd: Contains the primary commands defining entry points into the system.
- cmd/catchupsrv (README): A tool to assist with processing historic blocks on a new node.
- libgoal: Exports a Go interface useful for developers of Algorand clients.
- tools (README): Various tools and utilities that donât have a better place to go.
- tools/debug: Holds secondary commands that assist developers during debugging.
- tools/misc (README): Small tools that are handy in a pinch.
Deployment
Helps Algorand developers deploy networks of their own:
- nodecontrol
- docker
- commandandcontrol (README): A tool to automate a network of
algod
instances. - components
- netdeploy
Utilities
Provides utilities for the various components:
- logging: A wrapper around
logrus
. - util: Contains a variety of utilities, including a codec, a SQLite wrapper, a goroutine pool, a timer interface, node metrics, and more.
Test
- test (README): Contains end-to-end tests and utilities for the above components.
License
Please see the COPYING_FAQ for details on how to apply our license.
Copyright (C) 2019-2024, Algorand Inc.
Top Related Projects
Stellar's public monorepo of go code
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Go implementation of the Ethereum protocol
⟁ Tendermint Core (BFT Consensus) in Go
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot