Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract simnet btcwallet/btcd creation/config into new package #85

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/wire"
rpc "github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcsim/simnode"
"github.com/btcsuite/btcutil"
)

Expand All @@ -47,7 +48,7 @@ type utxoQueue struct {
// Actor describes an actor on the simulation network. Each actor runs
// independantly without external input to decide it's behavior.
type Actor struct {
*Node
*simnode.Node
quit chan struct{}
wg sync.WaitGroup
ownedAddresses []btcutil.Address
Expand All @@ -65,23 +66,23 @@ type TxOut struct {
// NewActor creates a new actor which runs its own wallet process connecting
// to the btcd node server specified by node, and listening for simulator
// websocket connections on the specified port.
func NewActor(node *Node, port uint16) (*Actor, error) {
func NewActor(node *simnode.Node, port uint16) (*Actor, error) {
// Please don't run this as root.
if port < 1024 {
return nil, errors.New("invalid actor port")
}

// Set btcwallet node args
args, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))
args, err := simnode.NewBtcwalletArgs(port, node.Args.(*simnode.BtcdArgs))
if err != nil {
return nil, err
}

logFile, err := getLogFile(args.prefix)
logFile, err := getLogFile(args.Prefix)
if err != nil {
log.Printf("Cannot get log file, logging disabled: %v", err)
}
btcwallet, err := NewNodeFromArgs(args, nil, logFile)
btcwallet, err := simnode.NewNodeFromArgs(args, nil, logFile, *maxConnRetries, AppDataDir)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -126,7 +127,7 @@ func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
connected <- struct{}{}
},
}
a.handlers = ntfnHandlers
a.Handlers = ntfnHandlers

if err := a.Connect(); err != nil {
a.Shutdown()
Expand All @@ -139,7 +140,7 @@ func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {

// Wait for wallet sync
for i := 0; i < *maxConnRetries; i++ {
if _, err := a.client.GetBalance(""); err != nil {
if _, err := a.Client.GetBalance(""); err != nil {
time.Sleep(time.Duration(i) * 50 * time.Millisecond)
continue
}
Expand All @@ -150,7 +151,7 @@ func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
log.Printf("%s: Creating wallet addresses...", a)
for i := range a.ownedAddresses {
fmt.Printf("\r%d/%d", i+1, len(a.ownedAddresses))
addr, err := a.client.GetNewAddress()
addr, err := a.Client.GetNewAddress()
if err != nil {
log.Printf("%s: Cannot create address #%d", a, i+1)
com.errChan <- struct{}{}
Expand All @@ -160,7 +161,7 @@ func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
}
fmt.Printf("\n")

if err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
if err := a.Client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
log.Printf("%s: Cannot unlock wallet: %v", a, err)
com.errChan <- struct{}{}
return err
Expand Down Expand Up @@ -310,20 +311,20 @@ func (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {

// sendRawTransaction creates a raw transaction, signs it and sends it
func (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {
msgTx, err := a.client.CreateRawTransaction(inputs, amounts)
msgTx, err := a.Client.CreateRawTransaction(inputs, amounts)
if err != nil {
return err
}
// sign it
msgTx, ok, err := a.client.SignRawTransaction(msgTx)
msgTx, ok, err := a.Client.SignRawTransaction(msgTx)
if err != nil {
return err
}
if !ok {
return err
}
// and finally send it.
if _, err := a.client.SendRawTransaction(msgTx, false); err != nil {
if _, err := a.Client.SendRawTransaction(msgTx, false); err != nil {
return err
}
return nil
Expand Down
9 changes: 5 additions & 4 deletions comm.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
rpc "github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcsim/simnode"
"github.com/btcsuite/btcutil"
)

Expand Down Expand Up @@ -89,7 +90,7 @@ func NewCommunication() *Communication {

// Start handles the main part of a simulation by starting
// all the necessary goroutines.
func (com *Communication) Start(actors []*Actor, node *Node, txCurve map[int32]*Row) (tpsChan chan float64, tpbChan chan int) {
func (com *Communication) Start(actors []*Actor, node *simnode.Node, txCurve map[int32]*Row) (tpsChan chan float64, tpbChan chan int) {
tpsChan = make(chan float64, 1)
tpbChan = make(chan int, 1)

Expand Down Expand Up @@ -138,7 +139,7 @@ func (com *Communication) Start(actors []*Actor, node *Node, txCurve map[int32]*
}

// Add mining node listen interface as a node
node.client.AddNode("localhost:18550", rpc.ANAdd)
node.Client.AddNode("localhost:18550", rpc.ANAdd)

// Start a goroutine to estimate tps
com.wg.Add(1)
Expand All @@ -156,7 +157,7 @@ func (com *Communication) Start(actors []*Actor, node *Node, txCurve map[int32]*
go com.queueBlocks()

com.wg.Add(1)
go com.poolUtxos(node.client, actors)
go com.poolUtxos(node.Client, actors)

// Start a goroutine for shuting down the simulation when appropriate
com.wg.Add(1)
Expand Down Expand Up @@ -587,7 +588,7 @@ func (com *Communication) Communicate(txCurve map[int32]*Row, miner *Miner, acto

// Shutdown shuts down the simulation by killing the mining and the
// initial node processes and shuts down all actors.
func (com *Communication) Shutdown(miner *Miner, actors []*Actor, node *Node) {
func (com *Communication) Shutdown(miner *Miner, actors []*Actor, node *simnode.Node) {
defer com.wg.Done()

<-com.exit
Expand Down
18 changes: 10 additions & 8 deletions miner.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@ import (

"github.com/btcsuite/btcd/wire"
rpc "github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcsim/simnode"
"github.com/btcsuite/btcutil"
)

// Miner holds all the core features required to register, run, control,
// and kill a cpu-mining btcd instance.
type Miner struct {
*Node
*simnode.Node
}

// NewMiner starts a cpu-mining enabled btcd instane and returns an rpc client
Expand Down Expand Up @@ -62,7 +63,7 @@ func NewMiner(miningAddrs []btcutil.Address, exit chan struct{},
}

log.Println("Starting miner on simnet...")
args, err := newBtcdArgs("miner")
args, err := simnode.NewBtcdArgs("miner", CertFile, KeyFile)
if err != nil {
return nil, err
}
Expand All @@ -83,11 +84,12 @@ func NewMiner(miningAddrs []btcutil.Address, exit chan struct{},
}
}

logFile, err := getLogFile(args.prefix)
logFile, err := getLogFile(args.Prefix)
if err != nil {
log.Printf("Cannot get log file, logging disabled: %v", err)
}
node, err := NewNodeFromArgs(args, ntfnHandlers, logFile)
node, err := simnode.NewNodeFromArgs(args, ntfnHandlers, logFile,
*maxConnRetries, AppDataDir)

miner := &Miner{
Node: node,
Expand All @@ -102,7 +104,7 @@ func NewMiner(miningAddrs []btcutil.Address, exit chan struct{},
}

// Register for transaction notifications
if err := miner.client.NotifyNewTransactions(false); err != nil {
if err := miner.Client.NotifyNewTransactions(false); err != nil {
log.Printf("%s: Cannot register for transactions notifications: %v", miner, err)
return miner, err
}
Expand All @@ -113,7 +115,7 @@ func NewMiner(miningAddrs []btcutil.Address, exit chan struct{},
}

// Register for block notifications.
if err := miner.client.NotifyBlocks(); err != nil {
if err := miner.Client.NotifyBlocks(); err != nil {
log.Printf("%s: Cannot register for block notifications: %v", miner, err)
return miner, err
}
Expand All @@ -124,7 +126,7 @@ func NewMiner(miningAddrs []btcutil.Address, exit chan struct{},

// StartMining sets the cpu miner to mine coins
func (m *Miner) StartMining() error {
if err := m.client.SetGenerate(true, 1); err != nil {
if err := m.Client.SetGenerate(true, 1); err != nil {
log.Printf("%s: Cannot start mining: %v", m, err)
return err
}
Expand All @@ -133,7 +135,7 @@ func (m *Miner) StartMining() error {

// StopMining stops the cpu miner from mining coins
func (m *Miner) StopMining() error {
if err := m.client.SetGenerate(false, 0); err != nil {
if err := m.Client.SetGenerate(false, 0); err != nil {
log.Printf("%s: Cannot stop mining: %v", m, err)
return err
}
Expand Down
49 changes: 29 additions & 20 deletions btcd.go → simnode/btcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

package main
package simnode

import (
"fmt"
Expand All @@ -28,9 +28,9 @@ import (
rpc "github.com/btcsuite/btcrpcclient"
)

// btcdArgs contains all the args and data required to launch a btcd
// BtcdArgs contains all the args and data required to launch a btcd
// instance and connect the rpc client to it
type btcdArgs struct {
type BtcdArgs struct {
RPCUser string
RPCPass string
Listen string
Expand All @@ -40,25 +40,30 @@ type btcdArgs struct {
LogDir string
Profile string
DebugLevel string
AddrIndex bool
Extra []string
Prefix string

prefix string
exe string
endpoint string
certFile string
keyFile string
certificates []byte
}

// newBtcdArgs returns a btcdArgs with all default values
func newBtcdArgs(prefix string) (*btcdArgs, error) {
a := &btcdArgs{
// newBtcdArgs returns a BtcdArgs with all default values
func NewBtcdArgs(prefix string, certFile, keyFile string) (*BtcdArgs, error) {
a := &BtcdArgs{
Listen: "127.0.0.1:18555",
RPCListen: "127.0.0.1:18556",
RPCUser: "user",
RPCPass: "pass",
Prefix: prefix,

prefix: prefix,
exe: "btcd",
endpoint: "ws",
certFile: certFile,
keyFile: keyFile,
}
if err := a.SetDefaults(); err != nil {
return nil, err
Expand All @@ -69,18 +74,18 @@ func newBtcdArgs(prefix string) (*btcdArgs, error) {
// SetDefaults sets the default values of args
// it creates tmp data and log directories and must
// be cleaned up by calling Cleanup
func (a *btcdArgs) SetDefaults() error {
datadir, err := ioutil.TempDir("", a.prefix+"-data")
func (a *BtcdArgs) SetDefaults() error {
datadir, err := ioutil.TempDir("", a.Prefix+"-data")
if err != nil {
return err
}
a.DataDir = datadir
logdir, err := ioutil.TempDir("", a.prefix+"-logs")
logdir, err := ioutil.TempDir("", a.Prefix+"-logs")
if err != nil {
return err
}
a.LogDir = logdir
cert, err := ioutil.ReadFile(CertFile)
cert, err := ioutil.ReadFile(a.certFile)
if err != nil {
return err
}
Expand All @@ -89,13 +94,13 @@ func (a *btcdArgs) SetDefaults() error {
}

// String returns a printable name of this instance
func (a *btcdArgs) String() string {
return a.prefix
func (a *BtcdArgs) String() string {
return a.Prefix
}

// Arguments returns an array of arguments that be used to launch the
// btcd instance
func (a *btcdArgs) Arguments() []string {
func (a *BtcdArgs) Arguments() []string {
args := []string{}
// --simnet
args = append(args, fmt.Sprintf("--%s", strings.ToLower(wire.SimNet.String())))
Expand All @@ -120,9 +125,13 @@ func (a *btcdArgs) Arguments() []string {
args = append(args, fmt.Sprintf("--rpcconnect=%s", a.RPCConnect))
}
// --rpccert
args = append(args, fmt.Sprintf("--rpccert=%s", CertFile))
args = append(args, fmt.Sprintf("--rpccert=%s", a.certFile))
// --rpckey
args = append(args, fmt.Sprintf("--rpckey=%s", KeyFile))
args = append(args, fmt.Sprintf("--rpckey=%s", a.keyFile))
if a.AddrIndex {
// --addrindex
args = append(args, fmt.Sprintf("--addrindex"))
}
if a.DataDir != "" {
// --datadir
args = append(args, fmt.Sprintf("--datadir=%s", a.DataDir))
Expand All @@ -144,13 +153,13 @@ func (a *btcdArgs) Arguments() []string {
}

// Command returns Cmd of the btcd instance
func (a *btcdArgs) Command() *exec.Cmd {
func (a *BtcdArgs) Command() *exec.Cmd {
return exec.Command(a.exe, a.Arguments()...)
}

// RPCConnConfig returns the rpc connection config that can be used
// to connect to the btcd instance that is launched on Start
func (a *btcdArgs) RPCConnConfig() rpc.ConnConfig {
func (a *BtcdArgs) RPCConnConfig() rpc.ConnConfig {
return rpc.ConnConfig{
Host: a.RPCListen,
Endpoint: a.endpoint,
Expand All @@ -162,7 +171,7 @@ func (a *btcdArgs) RPCConnConfig() rpc.ConnConfig {
}

// Cleanup removes the tmp data and log directories
func (a *btcdArgs) Cleanup() error {
func (a *BtcdArgs) Cleanup() error {
dirs := []string{
a.LogDir,
a.DataDir,
Expand Down
18 changes: 13 additions & 5 deletions btcd_test.go → simnode/btcd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,30 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

package main
package simnode

import "testing"
import (
"os"
"testing"
)

func TestnewBtcdArgs(t *testing.T) {
certFile := "rpc.cert"
keyFile := "rpc.key"
prefix := "miner"
err := genCertPair(CertFile, KeyFile)
err := GenCertPair(certFile, keyFile)
defer os.Remove(certFile)
defer os.Remove(keyFile)

if err != nil {
t.Errorf("genCertPair error: %v", err)
}
args, err := newBtcdArgs(prefix)
args, err := NewBtcdArgs(prefix, certFile, keyFile)
defer args.Cleanup()
if err != nil {
t.Errorf("newBtcdArgs error: %v", err)
}
expectedArgs := &btcdArgs{
expectedArgs := &BtcdArgs{
// fixed
Listen: "127.0.0.1:18555",
RPCListen: "127.0.0.1:18556",
Expand Down
Loading