本文整理匯總了Golang中github.com/FactomProject/factomd/state.State類的典型用法代碼示例。如果您正苦於以下問題:Golang State類的具體用法?Golang State怎麽用?Golang State使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了State類的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: CreateEmptyTestState
func CreateEmptyTestState() *state.State {
s := new(state.State)
s.LoadConfig("", "")
s.Init()
state.LoadDatabase(s)
return s
}
示例2: Factomd
func Factomd() {
log.Print("//////////////////////// Copyright 2015 Factom Foundation")
log.Print("//////////////////////// Use of this source code is governed by the MIT")
log.Print("//////////////////////// license that can be found in the LICENSE file.")
log.Printf("Go compiler version: %s\n", runtime.Version())
log.Printf("Using build: %s\n", Build)
if !isCompilerVersionOK() {
for i := 0; i < 30; i++ {
log.Println("!!! !!! !!! ERROR: unsupported compiler version !!! !!! !!!")
}
time.Sleep(3 * time.Second)
os.Exit(1)
}
// Go Optimizations...
runtime.GOMAXPROCS(runtime.NumCPU())
state0 := new(state.State)
state0.SetLeaderTimestamp(primitives.NewTimestampFromMilliseconds(0))
fmt.Println("len(Args)", len(os.Args))
NetStart(state0)
}
示例3: makeServer
//**********************************************************************
// Functions that access variables in this method to set up Factom Nodes
// and start the servers.
//**********************************************************************
func makeServer(s *state.State) *FactomNode {
// All other states are clones of the first state. Which this routine
// gets passed to it.
newState := s
if len(fnodes) > 0 {
newState = s.Clone(len(fnodes)).(*state.State)
time.Sleep(10 * time.Millisecond)
newState.Init()
}
fnode := new(FactomNode)
fnode.State = newState
fnodes = append(fnodes, fnode)
fnode.MLog = mLog
return fnode
}
示例4: setupFirstAuthority
func setupFirstAuthority(s *state.State) {
var id state.Identity
if networkIdentity := s.GetNetworkBootStrapIdentity(); networkIdentity != nil {
id.IdentityChainID = networkIdentity
} else {
id.IdentityChainID = primitives.NewZeroHash()
}
id.ManagementChainID, _ = primitives.HexToHash("88888800000000000000000000000000")
if pub := s.GetNetworkBootStrapKey(); pub != nil {
id.SigningKey = pub
} else {
id.SigningKey = primitives.NewZeroHash()
}
id.MatryoshkaHash = primitives.NewZeroHash()
id.ManagementCreated = 0
id.ManagementRegistered = 0
id.IdentityCreated = 0
id.IdentityRegistered = 0
id.Key1 = primitives.NewZeroHash()
id.Key2 = primitives.NewZeroHash()
id.Key3 = primitives.NewZeroHash()
id.Key4 = primitives.NewZeroHash()
id.Status = 1
s.Identities = append(s.Identities, &id)
var auth state.Authority
auth.Status = 1
auth.SigningKey = primitives.PubKeyFromString(id.SigningKey.String())
auth.MatryoshkaHash = primitives.NewZeroHash()
auth.AuthorityChainID = id.IdentityChainID
auth.ManagementChainID, _ = primitives.HexToHash("88888800000000000000000000000000")
s.Authorities = append(s.Authorities, &auth)
}
示例5: CreateAndPopulateTestState
func CreateAndPopulateTestState() *state.State {
s := new(state.State)
s.DB = CreateAndPopulateTestDatabaseOverlay()
s.Init("")
err := s.RecalculateBalances()
if err != nil {
panic(err)
}
s.FactoidState.SetFactoshisPerEC(1)
return s
}
示例6: main
func main() {
fmt.Println("Usage:")
fmt.Println("ReceiptGenerator level/bolt [EntryID-To-Extract]")
fmt.Println("Leave out the last one to export all entries")
if len(os.Args) < 1 {
fmt.Println("\nNot enough arguments passed")
os.Exit(1)
}
if len(os.Args) > 2 {
fmt.Println("\nToo many arguments passed")
os.Exit(1)
}
levelBolt := os.Args[1]
if levelBolt != level && levelBolt != bolt {
fmt.Println("\nFirst argument should be `level` or `bolt`")
os.Exit(1)
}
entryID := ""
if len(os.Args) == 3 {
entryID = os.Args[2]
}
state := new(state.State)
state.Cfg = util.ReadConfig("")
if levelBolt == level {
err := state.InitLevelDB()
if err != nil {
panic(err)
}
}
if levelBolt == bolt {
err := state.InitBoltDB()
if err != nil {
panic(err)
}
}
dbo := state.GetAndLockDB()
defer state.UnlockDB()
if entryID != "" {
err := ExportEntryReceipt(entryID, dbo)
if err != nil {
panic(err)
}
} else {
err := ExportAllEntryReceipts(dbo)
if err != nil {
panic(err)
}
}
}
示例7: TestSecretCode
func TestSecretCode(t *testing.T) {
s := new(state.State)
ts1 := s.GetTimestamp()
num1 := s.GetSalt(ts1)
num2 := s.GetSalt(ts1)
if num1 != num2 {
t.Error("Secret Number failure")
}
ts1.SetTime(uint64(ts1.GetTimeMilli() + 1000))
num3 := s.GetSalt(ts1)
if num1 == num3 {
t.Error("Secret Number bad match")
}
fmt.Printf("Secret Numbers %x %x %x\n", num1, num2, num3)
}
示例8: main
func main() {
fmt.Println("Usage:")
fmt.Println("BlockExtractor level/bolt [ChainID-To-Extract]")
fmt.Println("Leave out the last one to export basic chains (A, D, EC, F)")
if len(os.Args) < 1 {
fmt.Println("\nNot enough arguments passed")
os.Exit(1)
}
if len(os.Args) > 2 {
fmt.Println("\nToo many arguments passed")
os.Exit(1)
}
levelBolt := os.Args[1]
if levelBolt != level && levelBolt != bolt {
fmt.Println("\nFirst argument should be `level` or `bolt`")
os.Exit(1)
}
chainID := ""
if len(os.Args) == 3 {
chainID = os.Args[2]
}
state := new(state.State)
state.Cfg = util.ReadConfig("")
if levelBolt == level {
err := state.InitLevelDB()
if err != nil {
panic(err)
}
}
if levelBolt == bolt {
err := state.InitBoltDB()
if err != nil {
panic(err)
}
}
dbo := state.GetDB()
if chainID != "" {
err := ExportEChain(chainID, dbo)
if err != nil {
panic(err)
}
} else {
err := ExportDChain(dbo)
if err != nil {
panic(err)
}
err = ExportECChain(dbo)
if err != nil {
panic(err)
}
err = ExportAChain(dbo)
if err != nil {
panic(err)
}
err = ExportFctChain(dbo)
if err != nil {
panic(err)
}
err = ExportDirBlockInfo(dbo)
if err != nil {
panic(err)
}
}
}
示例9: main
func main() {
log.Print("//////////////////////// Copyright 2015 Factom Foundation")
log.Print("//////////////////////// Use of this source code is governed by the MIT")
log.Print("//////////////////////// license that can be found in the LICENSE file.")
log.Printf("Go compiler version: %s\n", runtime.Version())
log.Printf("Using build: %s\n", Build)
if !isCompilerVersionOK() {
for i := 0; i < 30; i++ {
fmt.Println("!!! !!! !!! ERROR: unsupported compiler version !!! !!! !!!")
}
time.Sleep(3 * time.Second)
os.Exit(1)
}
cfgFilename := ""
state := new(state.State)
state.Init(cfgFilename)
runtime.GOMAXPROCS(runtime.NumCPU())
if err := limits.SetLimits(); err != nil {
os.Exit(1)
}
btcd.AddInterruptHandler(func() {
log.Printf("Gracefully shutting down the database...")
state.GetDB().(interfaces.IDatabase).Close()
})
log.Print("Starting server")
server, _ := btcd.NewServer(state)
btcd.AddInterruptHandler(func() {
log.Printf("Gracefully shutting down the server...")
server.Stop()
server.WaitForShutdown()
})
server.Start()
state.SetServer(server)
//factomForkInit(server)
go NetworkProcessor(state)
go Timer(state)
go Validator(state)
go Leader(state)
go Follower(state)
go wsapi.Start(state)
shutdownChannel := make(chan struct{})
go func() {
server.WaitForShutdown()
log.Printf("Server shutdown complete")
shutdownChannel <- struct{}{}
}()
// Wait for shutdown signal from either a graceful server stop or from
// the interrupt handler.
<-shutdownChannel
log.Printf("Shutdown complete")
}
示例10: searchDB
func searchDB(searchitem string, st state.State) (bool, string) {
if len(searchitem) < 32 {
heightInt, err := strconv.Atoi(searchitem)
if err != nil {
return false, ""
}
height := uint32(heightInt)
if height < DisplayState.CurrentNodeHeight {
dbase := StatePointer.GetAndLockDB()
dBlock, err := dbase.FetchDBlockByHeight(height)
StatePointer.UnlockDB()
if err != nil {
return false, ""
}
resp := `{"Type":"dblockHeight","item":"` + dBlock.GetKeyMR().String() + `"}`
return true, resp
}
return false, ""
}
switch searchitem[:2] {
case "EC":
hash := base58.Decode(searchitem)
if len(hash) < 34 {
return false, ""
}
var fixed [32]byte
copy(fixed[:], hash[2:34])
bal := fmt.Sprintf("%d", st.FactoidState.GetECBalance(fixed))
return true, `{"Type":"EC","item":` + bal + "}"
case "FA":
hash := base58.Decode(searchitem)
if len(hash) < 34 {
return false, ""
}
var fixed [32]byte
copy(fixed[:], hash[2:34])
bal := fmt.Sprintf("%.8f", float64(st.FactoidState.GetFactoidBalance(fixed))/1e8)
return true, `{"Type":"FA","item":` + bal + "}"
}
if len(searchitem) == 64 {
hash, err := primitives.HexToHash(searchitem)
if err != nil {
return false, ""
}
// Must unlock manually when returining. Function continues to wsapi, who needs the dbase
dbase := st.GetAndLockDB()
// Search for Entry
if entry, err := dbase.FetchEntry(hash); err == nil && entry != nil {
resp := newSearchResponse("entry", entry)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for Chain
if mr, err := dbase.FetchHeadIndexByChainID(hash); err == nil && mr != nil {
resp := newSearchResponse("chainhead", mr)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for EBlock
if eBlock, err := dbase.FetchEBlockByPrimary(hash); err == nil && eBlock != nil {
resp := newSearchResponse("eblock", eBlock)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for DBlock
if dBlock, err := dbase.FetchDBlockByPrimary(hash); err == nil && dBlock != nil {
resp := newSearchResponse("dblock", dBlock)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for ABlock
if aBlock, err := dbase.FetchABlock(hash); err == nil && aBlock != nil {
resp := newSearchResponse("ablock", aBlock)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for Factoid Block
if fBlock, err := dbase.FetchFBlock(hash); err == nil && fBlock != nil {
resp := newSearchResponse("fblock", fBlock)
if len(resp) > 1 {
st.UnlockDB()
return true, resp
}
}
// Search for Entry Credit Block
if ecBlock, err := dbase.FetchECBlock(hash); err == nil && ecBlock != nil {
resp := newSearchResponse("ecblock", ecBlock)
if len(resp) > 1 {
//.........這裏部分代碼省略.........
示例11: NetStart
func NetStart(s *state.State) {
enablenetPtr := flag.Bool("enablenet", true, "Enable or disable networking")
listenToPtr := flag.Int("node", 0, "Node Number the simulator will set as the focus")
cntPtr := flag.Int("count", 1, "The number of nodes to generate")
netPtr := flag.String("net", "tree", "The default algorithm to build the network connections")
fnetPtr := flag.String("fnet", "", "Read the given file to build the network connections")
dropPtr := flag.Int("drop", 0, "Number of messages to drop out of every thousand")
journalPtr := flag.String("journal", "", "Rerun a Journal of messages")
journalingPtr := flag.Bool("journaling", false, "Write a journal of all messages recieved. Default is off.")
followerPtr := flag.Bool("follower", false, "If true, force node to be a follower. Only used when replaying a journal.")
leaderPtr := flag.Bool("leader", true, "If true, force node to be a leader. Only used when replaying a journal.")
dbPtr := flag.String("db", "", "Override the Database in the Config file and use this Database implementation")
cloneDBPtr := flag.String("clonedb", "", "Override the main node and use this database for the clones in a Network.")
portOverridePtr := flag.Int("port", 0, "Address to serve WSAPI on")
networkNamePtr := flag.String("network", "", "Network to join: MAIN, TEST or LOCAL")
networkPortOverridePtr := flag.Int("networkPort", 0, "Address for p2p network to listen on.")
peersPtr := flag.String("peers", "", "Array of peer addresses. ")
blkTimePtr := flag.Int("blktime", 0, "Seconds per block. Production is 600.")
runtimeLogPtr := flag.Bool("runtimeLog", false, "If true, maintain runtime logs of messages passed.")
netdebugPtr := flag.Int("netdebug", 0, "0-5: 0 = quiet, >0 = increasing levels of logging")
exclusivePtr := flag.Bool("exclusive", false, "If true, we only dial out to special/trusted peers.")
prefixNodePtr := flag.String("prefix", "", "Prefix the Factom Node Names with this value; used to create leaderless networks.")
rotatePtr := flag.Bool("rotate", false, "If true, responsiblity is owned by one leader, and rotated over the leaders.")
timeOffsetPtr := flag.Int("timedelta", 0, "Maximum timeDelta in milliseconds to offset each node. Simulates deltas in system clocks over a network.")
keepMismatchPtr := flag.Bool("keepmismatch", false, "If true, do not discard DBStates even when a majority of DBSignatures have a different hash")
startDelayPtr := flag.Int("startdelay", 10, "Delay to start processing messages, in seconds")
deadlinePtr := flag.Int("deadline", 1000, "Timeout Delay in milliseconds used on Reads and Writes to the network comm")
customNetPtr := flag.String("customnet", "", "This string specifies a custom blockchain network ID.")
rpcUserflag := flag.String("rpcuser", "", "Username to protect factomd local API with simple HTTP authentication")
rpcPasswordflag := flag.String("rpcpass", "", "Password to protect factomd local API. Ignored if rpcuser is blank")
factomdTLSflag := flag.Bool("tls", false, "Set to true to require encrypted connections to factomd API and Control Panel") //to get tls, run as "factomd -tls=true"
factomdLocationsflag := flag.String("selfaddr", "", "comma seperated IPAddresses and DNS names of this factomd to use when creating a cert file")
flag.Parse()
enableNet := *enablenetPtr
listenTo := *listenToPtr
cnt := *cntPtr
net := *netPtr
fnet := *fnetPtr
droprate := *dropPtr
journal := *journalPtr
journaling := *journalingPtr
follower := *followerPtr
leader := *leaderPtr
db := *dbPtr
cloneDB := *cloneDBPtr
portOverride := *portOverridePtr
peers := *peersPtr
networkName := *networkNamePtr
networkPortOverride := *networkPortOverridePtr
blkTime := *blkTimePtr
runtimeLog := *runtimeLogPtr
netdebug := *netdebugPtr
exclusive := *exclusivePtr
prefix := *prefixNodePtr
rotate := *rotatePtr
timeOffset := *timeOffsetPtr
keepMismatch := *keepMismatchPtr
startDelay := int64(*startDelayPtr)
deadline := *deadlinePtr
customNet := primitives.Sha([]byte(*customNetPtr)).Bytes()[:4]
rpcUser := *rpcUserflag
rpcPassword := *rpcPasswordflag
factomdTLS := *factomdTLSflag
factomdLocations := *factomdLocationsflag
// Must add the prefix before loading the configuration.
s.AddPrefix(prefix)
FactomConfigFilename := util.GetConfigFilename("m2")
fmt.Println(fmt.Sprintf("factom config: %s", FactomConfigFilename))
s.LoadConfig(FactomConfigFilename, networkName)
s.OneLeader = rotate
s.TimeOffset = primitives.NewTimestampFromMilliseconds(uint64(timeOffset))
s.StartDelayLimit = startDelay * 1000
s.Journaling = journaling
if 999 < portOverride { // The command line flag exists and seems reasonable.
s.SetPort(portOverride)
}
if blkTime != 0 {
s.DirectoryBlockInSeconds = blkTime
} else {
blkTime = s.DirectoryBlockInSeconds
}
if follower {
leader = false
}
if leader {
follower = false
}
if !follower && !leader {
panic("Not a leader or a follower")
}
if journal != "" {
cnt = 1
}
//.........這裏部分代碼省略.........
示例12: CreateAndPopulateTestState
func CreateAndPopulateTestState() *state.State {
s := new(state.State)
s.DB = CreateAndPopulateTestDatabaseOverlay()
s.LoadConfig("", "")
s.Init()
s.NetworkNumber = constants.NETWORK_MAIN
/*err := s.RecalculateBalances()
if err != nil {
panic(err)
}*/
s.SetFactoshisPerEC(1)
state.LoadDatabase(s)
s.UpdateState()
go s.ValidatorLoop()
time.Sleep(30 * time.Millisecond)
return s
}
示例13: CreateAndPopulateTestStateForFER
func CreateAndPopulateTestStateForFER(testEntries []FEREntryWithHeight, desiredHeight int) *state.State {
s := new(state.State)
s.DB = CreateAndPopulateTestDatabaseOverlayForFER(testEntries, desiredHeight)
s.LoadConfig("", "")
s.Init()
/*err := s.RecalculateBalances()
if err != nil {
panic(err)
}*/
s.SetFactoshisPerEC(1)
state.LoadDatabase(s)
s.FERChainId = "111111118d918a8be684e0dac725493a75862ef96d2d3f43f84b26969329bf03"
s.UpdateState()
go s.ValidatorLoop()
time.Sleep(20 * time.Millisecond)
return s
}