本文整理匯總了Golang中github.com/NebulousLabs/Sia/sync.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: New
// New returns a host database that will still crawling the hosts it finds on
// the blockchain.
func New(cs *consensus.ConsensusSet, g modules.Gateway) (hdb *HostDB, err error) {
// Check for nil dependencies.
if cs == nil {
err = ErrNilConsensusSet
return
}
if g == nil {
err = ErrNilGateway
return
}
// Build an empty hostdb.
hdb = &HostDB{
consensusSet: cs,
gateway: g,
activeHosts: make(map[modules.NetAddress]*hostNode),
allHosts: make(map[modules.NetAddress]*hostEntry),
scanPool: make(chan *hostEntry, scanPoolSize),
mu: sync.New(modules.SafeMutexDelay, 1),
}
// Begin listening to consensus and looking for hosts.
for i := 0; i < scanningThreads; i++ {
go hdb.threadedProbeHosts()
}
go hdb.threadedScan()
cs.ConsensusSetSubscribe(hdb)
return
}
示例2: NewServer
// NewServer creates a new API server from the provided modules.
func NewServer(APIaddr string, s *consensus.ConsensusSet, g modules.Gateway, h modules.Host, m modules.Miner, r modules.Renter, tp modules.TransactionPool, w modules.Wallet, explorer modules.Explorer) (*Server, error) {
l, err := net.Listen("tcp", APIaddr)
if err != nil {
return nil, err
}
srv := &Server{
cs: s,
gateway: g,
host: h,
miner: m,
renter: r,
tpool: tp,
wallet: w,
explorer: explorer,
listener: l,
mu: sync.New(modules.SafeMutexDelay, 1),
}
// Register API handlers
srv.initAPI()
return srv, nil
}
示例3: New
// New creates a new wallet, loading any known addresses from the input file
// name and then using the file to save in the future. Keys and addresses are
// not loaded into the wallet during the call to 'new', but rather during the
// call to 'Unlock'.
func New(cs modules.ConsensusSet, tpool modules.TransactionPool, persistDir string) (*Wallet, error) {
// Check for nil dependencies.
if cs == nil {
return nil, errNilConsensusSet
}
if tpool == nil {
return nil, errNilTpool
}
// Initialize the data structure.
w := &Wallet{
cs: cs,
tpool: tpool,
keys: make(map[types.UnlockHash]spendableKey),
siacoinOutputs: make(map[types.SiacoinOutputID]types.SiacoinOutput),
siafundOutputs: make(map[types.SiafundOutputID]types.SiafundOutput),
spentOutputs: make(map[types.OutputID]types.BlockHeight),
processedTransactionMap: make(map[types.TransactionID]*modules.ProcessedTransaction),
historicOutputs: make(map[types.OutputID]types.Currency),
historicClaimStarts: make(map[types.SiafundOutputID]types.Currency),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 1),
}
err := w.initPersist()
if err != nil {
return nil, err
}
return w, nil
}
示例4: TestRepeatInsert
// TestRepeatInsert inserts 2 hosts with the same address.
func TestRepeatInsert(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
hdb := &HostDB{
activeHosts: make(map[modules.NetAddress]*hostNode),
allHosts: make(map[modules.NetAddress]*hostEntry),
scanPool: make(chan *hostEntry, scanPoolSize),
mu: sync.New(modules.SafeMutexDelay, 1),
}
entry1 := hostEntry{
HostSettings: modules.HostSettings{IPAddress: fakeAddr(0)},
weight: types.NewCurrency64(1),
}
entry2 := entry1
hdb.insertNode(&entry1)
entry2.weight = types.NewCurrency64(100)
hdb.insertNode(&entry2)
if len(hdb.activeHosts) != 1 {
t.Error("insterting the same entry twice should result in only 1 entry in the hostdb")
}
}
示例5: NewServer
// NewServer creates a new API server from the provided modules.
func NewServer(APIaddr string, s *consensus.ConsensusSet, g modules.Gateway, h modules.Host, hdb modules.HostDB, m modules.Miner, r modules.Renter, tp modules.TransactionPool, w modules.Wallet, exp modules.Explorer) (*Server, error) {
l, err := net.Listen("tcp", APIaddr)
if err != nil {
return nil, err
}
srv := &Server{
cs: s,
gateway: g,
host: h,
hostdb: hdb,
miner: m,
renter: r,
tpool: tp,
wallet: w,
exp: exp,
blockchainHeight: -1,
listener: l,
mu: sync.New(modules.SafeMutexDelay, 1),
}
// Set the genesis block and start listening to the consensus package.
srv.currentBlock = srv.cs.GenesisBlock()
srv.cs.ConsensusSetSubscribe(srv)
// Register API handlers
srv.initAPI()
return srv, nil
}
示例6: New
// New creates a transaction pool that is ready to receive transactions.
func New(cs modules.ConsensusSet, g modules.Gateway) (*TransactionPool, error) {
// Check that the input modules are non-nil.
if cs == nil {
return nil, errNilCS
}
if g == nil {
return nil, errNilGateway
}
// Initialize a transaction pool.
tp := &TransactionPool{
consensusSet: cs,
gateway: g,
knownObjects: make(map[ObjectID]TransactionSetID),
transactionSets: make(map[TransactionSetID][]types.Transaction),
transactionSetDiffs: make(map[TransactionSetID]modules.ConsensusChange),
// The consensus change index is intialized to '-1', which indicates
// that no consensus changes have been sent yet. The first consensus
// change will then have an index of '0'.
consensusChangeIndex: -1,
mu: sync.New(modules.SafeMutexDelay, 5),
}
// Register RPCs
g.RegisterRPC("RelayTransactionSet", tp.RelayTransactionSet)
g.RegisterRPC("RelayTransaction", tp.RelayTransaction) // COMPAT v0.3.3.3
// Subscribe the transaction pool to the consensus set.
cs.ConsensusSetSubscribe(tp)
return tp, nil
}
示例7: New
// New returns an empty renter.
func New(cs modules.ConsensusSet, wallet modules.Wallet, tpool modules.TransactionPool, persistDir string) (*Renter, error) {
hdb, err := hostdb.New(cs, wallet, tpool, persistDir)
if err != nil {
return nil, err
}
r := &Renter{
cs: cs,
wallet: wallet,
hostDB: hdb,
files: make(map[string]*file),
tracking: make(map[string]trackedFile),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 1),
}
err = r.initPersist()
if err != nil {
return nil, err
}
go r.threadedRepairLoop()
return r, nil
}
示例8: New
// New returns an initialized Gateway.
func New(addr string, persistDir string) (g *Gateway, err error) {
// Create the directory if it doesn't exist.
err = os.MkdirAll(persistDir, 0700)
if err != nil {
return
}
// Create the logger.
logger, err := makeLogger(persistDir)
if err != nil {
return
}
g = &Gateway{
handlers: make(map[rpcID]modules.RPCFunc),
initRPCs: make(map[string]modules.RPCFunc),
peers: make(map[modules.NetAddress]*peer),
nodes: make(map[modules.NetAddress]struct{}),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 2),
log: logger,
}
// Load the old peer list. If it doesn't exist, no problem, but if it does,
// we want to know about any errors preventing us from loading it.
if loadErr := g.load(); loadErr != nil && !os.IsNotExist(loadErr) {
return nil, loadErr
}
// Create listener and set address.
g.listener, err = net.Listen("tcp", addr)
if err != nil {
return
}
_, port, _ := net.SplitHostPort(g.listener.Addr().String())
g.myAddr = modules.NetAddress(net.JoinHostPort("::1", port))
// Register RPCs.
g.RegisterRPC("ShareNodes", g.shareNodes)
g.RegisterRPC("RelayNode", g.relayNode)
g.RegisterConnectCall("ShareNodes", g.requestNodes)
g.log.Println("INFO: gateway created, started logging")
// Learn our external IP.
go g.learnHostname()
// Automatically forward the RPC port, if possible.
go g.forwardPort(port)
// Spawn the peer and node managers. These will attempt to keep the peer
// and node lists healthy.
go g.threadedPeerManager()
go g.threadedNodeManager()
// Spawn the primary listener.
go g.listen()
return
}
示例9: TestVariedWeights
// TestVariedWeights runs broad statistical tests on selecting hosts with
// multiple different weights.
func TestVariedWeights(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
hdb := &HostDB{
activeHosts: make(map[modules.NetAddress]*hostNode),
allHosts: make(map[modules.NetAddress]*hostEntry),
scanPool: make(chan *hostEntry, scanPoolSize),
mu: sync.New(modules.SafeMutexDelay, 1),
}
// insert i hosts with the weights 0, 1, ..., i-1. 100e3 selections will be made
// per weight added to the tree, the total number of selections necessary
// will be tallied up as hosts are created.
hostCount := 5
expectedPerWeight := int(10e3)
selections := 0
for i := 0; i < hostCount; i++ {
entry := hostEntry{
HostSettings: modules.HostSettings{IPAddress: fakeAddr(uint8(i))},
weight: types.NewCurrency64(uint64(i)),
}
hdb.insertNode(&entry)
selections += i * expectedPerWeight
}
// Perform many random selections, noting which host was selected each
// time.
selectionMap := make(map[string]int)
for i := 0; i < selections; i++ {
randEntry := hdb.RandomHosts(1)
if len(randEntry) == 0 {
t.Fatal("no hosts!")
}
node, exists := hdb.activeHosts[randEntry[0].IPAddress]
if !exists {
t.Fatal("can't find randomly selected node in tree")
}
selectionMap[node.hostEntry.weight.String()] += 1
}
// Check that each host was selected an expected number of times. An error
// will be reported if the host of 0 weight is ever selected.
acceptableError := 0.2
for weight, timesSelected := range selectionMap {
intWeight, err := strconv.Atoi(weight)
if err != nil {
t.Fatal(err)
}
expectedSelected := float64(intWeight * expectedPerWeight)
if float64(expectedSelected)*acceptableError > float64(timesSelected) || float64(expectedSelected)/acceptableError < float64(timesSelected) {
t.Error("weighted list not selecting in a uniform distribution based on weight")
t.Error(expectedSelected)
t.Error(timesSelected)
}
}
}
示例10: New
// New returns an initialized Gateway.
func New(addr string, persistDir string) (g *Gateway, err error) {
// Create the directory if it doesn't exist.
err = os.MkdirAll(persistDir, 0700)
if err != nil {
return
}
// Create the logger.
logger, err := makeLogger(persistDir)
if err != nil {
return
}
g = &Gateway{
handlers: make(map[rpcID]modules.RPCFunc),
initRPCs: make(map[string]modules.RPCFunc),
peers: make(map[modules.NetAddress]*peer),
nodes: make(map[modules.NetAddress]struct{}),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 2),
log: logger,
}
// Register RPCs.
g.RegisterRPC("ShareNodes", g.shareNodes)
g.RegisterRPC("RelayNode", g.relayNode)
g.RegisterConnectCall("ShareNodes", g.requestNodes)
g.RegisterConnectCall("RelayNode", g.sendAddress)
g.log.Println("INFO: gateway created, started logging")
// Create listener and set address.
g.listener, err = net.Listen("tcp", addr)
if err != nil {
return
}
_, port, _ := net.SplitHostPort(g.listener.Addr().String())
g.myAddr = modules.NetAddress(net.JoinHostPort(modules.ExternalIP, port))
g.log.Println("INFO: our address is", g.myAddr)
// Spawn the primary listener.
go g.listen()
// Load the old peer list. If it doesn't exist, no problem, but if it does,
// we want to know about any errors preventing us from loading it.
if loadErr := g.load(); loadErr != nil && !os.IsNotExist(loadErr) {
return nil, loadErr
}
// Spawn the connector loop. This will continually attempt to add nodes as
// peers to ensure we stay well-connected.
go g.makeOutboundConnections()
return
}
示例11: New
// New creates a new wallet, loading any known addresses from the input file
// name and then using the file to save in the future.
func New(cs modules.ConsensusSet, tpool modules.TransactionPool, saveDir string) (w *Wallet, err error) {
if cs == nil {
err = errors.New("wallet cannot use a nil state")
return
}
if tpool == nil {
err = errors.New("wallet cannot use a nil transaction pool")
return
}
w = &Wallet{
state: cs,
tpool: tpool,
saveDir: saveDir,
age: AgeDelay + 100,
keys: make(map[types.UnlockHash]*key),
timelockedKeys: make(map[types.BlockHeight][]types.UnlockHash),
visibleAddresses: make(map[types.UnlockHash]struct{}),
siafundAddresses: make(map[types.UnlockHash]struct{}),
siafundOutputs: make(map[types.SiafundOutputID]types.SiafundOutput),
transactions: make(map[string]*openTransaction),
mu: sync.New(modules.SafeMutexDelay, 1),
}
// Create the wallet folder.
err = os.MkdirAll(saveDir, 0700)
if err != nil {
return
}
// Try to load a previously saved wallet file. If it doesn't exist, assume
// that we're creating a new wallet file.
// TODO: log warning if no file found?
err = w.load()
if os.IsNotExist(err) {
err = nil
// No wallet file exists... make a visible address for the user.
_, _, err = w.coinAddress(true)
if err != nil {
return nil, err
}
}
if err != nil {
err = fmt.Errorf("couldn't load wallet file %s: %v", saveDir, err)
return
}
w.tpool.TransactionPoolSubscribe(w)
return
}
示例12: New
// New returns a ready-to-go miner that is not mining.
func New(cs modules.ConsensusSet, tpool modules.TransactionPool, w modules.Wallet, persistDir string) (*Miner, error) {
// Create the miner and its dependencies.
if cs == nil {
return nil, errors.New("miner cannot use a nil state")
}
if tpool == nil {
return nil, errors.New("miner cannot use a nil transaction pool")
}
if w == nil {
return nil, errors.New("miner cannot use a nil wallet")
}
// Grab some starting block variables.
currentBlock := cs.GenesisBlock().ID()
currentTarget, exists1 := cs.ChildTarget(currentBlock)
earliestTimestamp, exists2 := cs.EarliestChildTimestamp(currentBlock)
if build.DEBUG {
if !exists1 {
panic("could not get child target")
}
if !exists2 {
panic("could not get child earliest timestamp")
}
}
addr, _, err := w.CoinAddress(false) // false indicates that the address should not be visible to the user.
if err != nil {
return nil, err
}
// Assemble the miner.
m := &Miner{
cs: cs,
tpool: tpool,
wallet: w,
parent: currentBlock,
target: currentTarget,
earliestTimestamp: earliestTimestamp,
address: addr,
blockMem: make(map[types.BlockHeader]types.Block),
headerMem: make([]types.BlockHeader, headerForWorkMemory),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 1),
}
err = m.initPersist()
if err != nil {
return nil, err
}
m.tpool.TransactionPoolSubscribe(m)
return m, nil
}
示例13: New
// New returns a ready-to-go miner that is not mining.
func New(cs modules.ConsensusSet, tpool modules.TransactionPool, w modules.Wallet, persistDir string) (*Miner, error) {
// Create the miner and its dependencies.
if cs == nil {
return nil, errors.New("miner cannot use a nil state")
}
if tpool == nil {
return nil, errors.New("miner cannot use a nil transaction pool")
}
if w == nil {
return nil, errors.New("miner cannot use a nil wallet")
}
// Grab some starting block variables.
currentBlock := cs.GenesisBlock().ID()
currentTarget, exists1 := cs.ChildTarget(currentBlock)
earliestTimestamp, exists2 := cs.EarliestChildTimestamp(currentBlock)
if build.DEBUG {
if !exists1 {
panic("could not get child target")
}
if !exists2 {
panic("could not get child earliest timestamp")
}
}
// Assemble the miner. The miner is assembled without an address because
// the wallet is likely not unlocked yet. The miner will grab an address
// after the miner is unlocked (this must be coded manually for each
// function that potentially requires the miner to have an address.
m := &Miner{
cs: cs,
tpool: tpool,
wallet: w,
parent: currentBlock,
target: currentTarget,
earliestTimestamp: earliestTimestamp,
blockMem: make(map[types.BlockHeader]*types.Block),
arbDataMem: make(map[types.BlockHeader][]byte),
headerMem: make([]types.BlockHeader, headerForWorkMemory),
persistDir: persistDir,
mu: sync.New(modules.SafeMutexDelay, 1),
}
err := m.initPersist()
if err != nil {
return nil, err
}
m.tpool.TransactionPoolSubscribe(m)
return m, nil
}
示例14: New
// New creates and starts up a hostdb. The hostdb that gets returned will not
// have finished scanning the network or blockchain.
func New() *HostDB {
hdb := &HostDB{
activeHosts: make(map[modules.NetAddress]*hostNode),
allHosts: make(map[modules.NetAddress]*hostEntry),
scanPool: make(chan *hostEntry, scanPoolSize),
mu: sync.New(modules.SafeMutexDelay, 1),
}
// Begin listening to consensus and looking for hosts.
for i := 0; i < scanningThreads; i++ {
go hdb.threadedProbeHosts()
}
go hdb.threadedScan()
return hdb
}
示例15: New
// New returns an empty renter.
func New(cs modules.ConsensusSet, hdb modules.HostDB, wallet modules.Wallet, tpool modules.TransactionPool, saveDir string) (*Renter, error) {
if cs == nil {
return nil, ErrNilCS
}
if hdb == nil {
return nil, ErrNilHostDB
}
if wallet == nil {
return nil, ErrNilWallet
}
if tpool == nil {
return nil, ErrNilTpool
}
r := &Renter{
cs: cs,
hostDB: hdb,
wallet: wallet,
tpool: tpool,
files: make(map[string]*file),
contracts: make(map[types.FileContractID]types.FileContract),
saveDir: saveDir,
mu: sync.New(modules.SafeMutexDelay, 1),
}
_, err := rand.Read(r.entropy[:])
if err != nil {
return nil, err
}
err = os.MkdirAll(saveDir, 0700)
if err != nil {
return nil, err
}
err = r.load()
if err != nil && !os.IsNotExist(err) {
return nil, err
}
r.cs.ConsensusSetSubscribe(r)
return r, nil
}