func (m *FullServerFault) SigTally(state interfaces.IState) int {
	validSigCount := 0
	// Check main signature
	bytes, err := m.MarshalForSignature()
	if err != nil {
		return 0
	}
	sig := m.Signature.GetSignature()
	sfSigned, err := state.VerifyAuthoritySignature(bytes, sig, m.DBHeight)
	if err != nil {
		return 0
	}
	if sfSigned < 1 {
		return 0
	}
	cb, err := m.MarshalCore()
	if err != nil {
		return 0
	}
	for _, fedSig := range m.SignatureList.List {
		check, err := state.VerifyAuthoritySignature(cb, fedSig.GetSignature(), m.DBHeight)
		if err == nil && check == 1 {
			validSigCount++
		}
	}
	return validSigCount
}
Exemple #2
0
func HandleV2FactoidSubmit(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	t := new(TransactionRequest)
	err := MapToObject(params, t)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	msg := new(messages.FactoidTransaction)

	p, err := hex.DecodeString(t.Transaction)
	if err != nil {
		return nil, NewUnableToDecodeTransactionError()
	}

	_, err = msg.UnmarshalTransData(p)
	if err != nil {
		return nil, NewUnableToDecodeTransactionError()
	}

	state.IncFCTSubmits()

	state.APIQueue() <- msg

	resp := new(FactoidSubmitResponse)
	resp.Message = "Successfully submitted the transaction"
	resp.TxID = msg.Transaction.GetSigHash().String()

	return resp, nil
}
Exemple #3
0
func (m *MsgLog) PrtMsgs(state interfaces.IState) {
	m.sem.Lock()
	defer m.sem.Unlock()

	if len(m.MsgList) == 0 {
		return
	}

	fmt.Println(state.String())
	fmt.Println("\n-----------------------------------------------------")

	for _, e := range m.MsgList {
		if e.valid {

			dirstr := "->"
			if !e.out {
				dirstr = "<-"
			}

			fmt.Print(fmt.Sprintf("**** %8s %2s %8s %10s %5v     **** %s\n", e.name, dirstr, e.peer, e.where, e.valid, e.msg.String()))

		}
	}
	now := state.GetTimestamp()
	m.last = now
	m.msgCnt += len(m.MsgList) // Keep my counts
	m.msgCntp += len(m.MsgList)
	m.MsgList = m.MsgList[0:0] // Once printed, clear the list

	fmt.Println(fmt.Sprintf("*** %42s **** ", fmt.Sprintf("Length: %d    Msgs/sec: T %d P %d", len(m.MsgList), m.msgPerSec, m.msgPerSecp)))
	fmt.Println("\n-----------------------------------------------------")
}
Exemple #4
0
// Validate the message, given the state.  Three possible results:
//  < 0 -- Message is invalid.  Discard
//  0   -- Cannot tell if message is Valid
//  1   -- Message is valid
func (m *Ack) Validate(state interfaces.IState) int {

	if m.authvalid {
		return 1
	}

	// Only new acks are valid. Of course, the VMIndex has to be valid too.
	msg, err := state.GetMsg(m.VMIndex, int(m.DBHeight), int(m.Height))
	if err != nil || msg != nil {
		return -1
	}

	// Check signature
	bytes, err := m.MarshalForSignature()
	if err != nil {
		//fmt.Println("Err is not nil on Ack sig check: ", err)
		return -1
	}
	sig := m.Signature.GetSignature()
	ackSigned, err := state.VerifyAuthoritySignature(bytes, sig, m.DBHeight)

	//ackSigned, err := m.VerifySignature()
	if err != nil {
		//fmt.Println("Err is not nil on Ack sig check: ", err)
		return -1
	}
	if ackSigned < 1 {
		return -1
	}
	m.authvalid = true
	return 1
}
Exemple #5
0
func (m *MissingData) FollowerExecute(state interfaces.IState) {
	var dataObject interfaces.BinaryMarshallable
	//var dataHash interfaces.IHash
	rawObject, dataType, err := state.LoadDataByHash(m.RequestHash)

	if rawObject != nil && err == nil { // If I don't have this message, ignore.
		switch dataType {
		case 0: // DataType = entry
			dataObject = rawObject.(interfaces.IEBEntry)
			//dataHash = dataObject.(interfaces.IEBEntry).GetHash()
		case 1: // DataType = eblock
			dataObject = rawObject.(interfaces.IEntryBlock)
			//dataHash, _ = dataObject.(interfaces.IEntryBlock).Hash()
		default:
			return
		}

		msg := NewDataResponse(state, dataObject, dataType, m.RequestHash)

		msg.SetOrigin(m.GetOrigin())
		msg.SetNetworkOrigin(m.GetNetworkOrigin())
		msg.SendOut(state, msg)
	}
	return
}
Exemple #6
0
func HandleV2CommitEntry(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	commitEntryMsg := new(EntryRequest)
	err := MapToObject(params, commitEntryMsg)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	commit := entryCreditBlock.NewCommitEntry()
	if p, err := hex.DecodeString(commitEntryMsg.Entry); err != nil {
		return nil, NewInvalidCommitEntryError()
	} else {
		_, err := commit.UnmarshalBinaryData(p)
		if err != nil {
			return nil, NewInvalidCommitEntryError()
		}
	}

	msg := new(messages.CommitEntryMsg)
	msg.CommitEntry = commit
	state.APIQueue() <- msg
	state.IncECommits()

	resp := new(CommitEntryResponse)
	resp.Message = "Entry Commit Success"
	resp.TxID = commit.GetSigHash().String()

	return resp, nil
}
Exemple #7
0
func HandleV2FactoidBalance(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	fadr := new(AddressRequest)
	err := MapToObject(params, fadr)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	var adr []byte

	if primitives.ValidateFUserStr(fadr.Address) {
		adr = primitives.ConvertUserStrToAddress(fadr.Address)
	} else {
		adr, err = hex.DecodeString(fadr.Address)
		if err == nil && len(adr) != constants.HASH_LENGTH {
			return nil, NewInvalidAddressError()
		}
		if err != nil {
			return nil, NewInvalidAddressError()
		}
	}

	if len(adr) != constants.HASH_LENGTH {
		return nil, NewInvalidAddressError()
	}

	resp := new(FactoidBalanceResponse)
	resp.Balance = state.GetFactoidState().GetFactoidBalance(factoid.NewAddress(adr).Fixed())
	return resp, nil
}
Exemple #8
0
// Validate the message, given the state.  Three possible results:
//  < 0 -- Message is invalid.  Discard
//  0   -- Cannot tell if message is Valid
//  1   -- Message is valid
func (m *DBStateMsg) Validate(state interfaces.IState) int {
	if m.DirectoryBlock == nil || m.AdminBlock == nil || m.FactoidBlock == nil || m.EntryCreditBlock == nil {
		//We need the basic block types
		return -1
	}

	if state.GetNetworkID() != m.DirectoryBlock.GetHeader().GetNetworkID() {
		//Wrong network ID
		return -1
	}

	dbheight := m.DirectoryBlock.GetHeader().GetDBHeight()

	if dbheight != state.GetHighestCompletedBlock()+1 && dbheight != 0 {
		//We only expect the next height
		return -1
	}

	if m.DirectoryBlock.GetHeader().GetNetworkID() == constants.MAIN_NETWORK_ID {
		key := constants.CheckPoints[dbheight]
		if key != "" {
			if key != m.DirectoryBlock.DatabasePrimaryIndex().String() {
				//Key does not match checkpoint
				return -1
			}
		}
	}
	return 1
}
Exemple #9
0
func (m *CommitChainMsg) FollowerExecute(state interfaces.IState) error {
	err := state.MatchAckFollowerExecute(m)
	if err != nil {
		return err
	}
	return nil
}
Exemple #10
0
func HandleV2RevealEntry(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	e := new(EntryRequest)
	err := MapToObject(params, e)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	entry := entryBlock.NewEntry()
	if p, err := hex.DecodeString(e.Entry); err != nil {
		return nil, NewInvalidEntryError()
	} else {
		_, err := entry.UnmarshalBinaryData(p)
		if err != nil {
			return nil, NewInvalidEntryError()
		}
	}

	msg := new(messages.RevealEntryMsg)
	msg.Entry = entry
	msg.Timestamp = state.GetTimestamp()
	state.APIQueue() <- msg

	resp := new(RevealEntryResponse)
	resp.Message = "Entry Reveal Success"
	resp.EntryHash = entry.GetHash().String()

	return resp, nil
}
func NewEntryBlockResponse(state interfaces.IState) interfaces.IMsg {
	msg := new(EntryBlockResponse)

	msg.Peer2Peer = true // Always a peer2peer request.
	msg.Timestamp = state.GetTimestamp()

	return msg
}
Exemple #12
0
func NewAddServerByHashMsg(state interfaces.IState, serverType int, newServerHash interfaces.IHash) interfaces.IMsg {
	msg := new(AddServerMsg)
	msg.ServerChainID = newServerHash
	msg.ServerType = serverType
	msg.Timestamp = state.GetTimestamp()

	return msg
}
// Validate the message, given the state.  Three possible results:
//  < 0 -- Message is invalid.  Discard
//  0   -- Cannot tell if message is Valid
//  1   -- Message is valid
func (m *FactoidTransaction) Validate(state interfaces.IState) int {
	err := state.GetFactoidState().Validate(1, m.Transaction)
	if err != nil {
		fmt.Println(err.Error())
		return -1
	}
	return 1
}
Exemple #14
0
func (m *RevealEntryMsg) Validate(state interfaces.IState) int {
	commit, rtn := m.ValidateRTN(state)
	if rtn == 1 {
		// Don't lose the commit that validates the entry
		state.PutCommit(m.Entry.GetHash(), commit)
	}
	return rtn
}
Exemple #15
0
func NewAddServerMsg(state interfaces.IState, serverType int) interfaces.IMsg {
	msg := new(AddServerMsg)
	msg.ServerChainID = state.GetIdentityChainID()
	msg.ServerType = serverType
	msg.Timestamp = state.GetTimestamp()

	return msg

}
Exemple #16
0
func NewRemoveServerMsg(state interfaces.IState, chainId interfaces.IHash, serverType int) interfaces.IMsg {
	msg := new(RemoveServerMsg)
	msg.ServerChainID = chainId
	msg.ServerType = serverType
	msg.Timestamp = state.GetTimestamp()

	return msg

}
Exemple #17
0
// btcdMain is the real main function for btcd.  It is necessary to work around
// the fact that deferred functions do not run when os.Exit() is called.  The
// optional serverChan parameter is mainly used by the service code to be
// notified with the server once it is setup so it can gracefully stop it when
// requested from the service control manager.
//func btcdMain(serverChan chan<- *server) error {
func btcdMain(serverChan chan<- *Server, state interfaces.IState) error {

	// Load configuration and parse command line.  This function also
	// initializes logging and configures it accordingly.
	tcfg, _, err := loadConfig()
	if err != nil {
		return err
	}
	cfg = tcfg
	// tweak some config options
	cfg.DisableCheckpoints = true
	defer backendLog.Flush()

	// Show version at startup.
	btcdLog.Infof("Version %s", version())

	// Ensure the database is sync'd and closed on Ctrl+C.
	AddInterruptHandler(func() {
		btcdLog.Infof("Gracefully shutting down the database...")
		state.GetDB().(interfaces.IDatabase).Close() //db.RollbackClose()
	})

	// Create server and start it.
	server, err := newServer(cfg.Listeners, activeNetParams.Params, state)
	if err != nil {
		// TODO(oga) this logging could do with some beautifying.
		btcdLog.Errorf("Unable to start server on %v: %v",
			cfg.Listeners, err)
		return err
	}
	AddInterruptHandler(func() {
		btcdLog.Infof("Gracefully shutting down the server...")
		server.Stop()
		server.WaitForShutdown()
	})
	server.Start()
	if serverChan != nil {
		serverChan <- server
	}

	// Factom Additions BEGIN
	//factomForkInit(server)
	// Factom Additions END

	go func() {
		server.WaitForShutdown()
		srvrLog.Infof("Server shutdown complete")
		shutdownChannel <- struct{}{}
	}()

	// Wait for shutdown signal from either a graceful server stop or from
	// the interrupt handler.
	<-shutdownChannel
	btcdLog.Info("Shutdown complete")
	return nil
}
func NewDBStateMissing(state interfaces.IState, dbheightStart uint32, dbheightEnd uint32) interfaces.IMsg {
	msg := new(DBStateMissing)

	msg.Peer2Peer = true // Always a peer2peer request.
	msg.Timestamp = state.GetTimestamp()
	msg.DBHeightStart = dbheightStart
	msg.DBHeightEnd = dbheightEnd

	return msg
}
Exemple #19
0
func (m *RemoveServerMsg) Validate(state interfaces.IState) int {
	// Check to see if identity exists and is audit or fed server
	if !state.VerifyIsAuthority(m.ServerChainID) {
		//fmt.Printf("RemoveServerMsg Error: [%s] is not a server, cannot be removed\n", m.ServerChainID.String()[:8])
		return -1
	}

	// TODO: Check valid signatures
	return 1
}
Exemple #20
0
// Try and Resend.  Return true if we should keep the message, false if we should give up.
func (m *MessageBase) Expire(s interfaces.IState) (rtn bool) {
	now := s.GetTimestamp().GetTimeMilli()
	if m.expire == 0 {
		m.expire = now
	}
	if now-m.expire > 5*60*1000 { // Keep messages for some length before giving up.
		rtn = true
	}
	return
}
Exemple #21
0
func NewMissingData(state interfaces.IState, requestHash interfaces.IHash) interfaces.IMsg {

	msg := new(MissingData)

	msg.Peer2Peer = true // Always a peer2peer request.
	msg.Timestamp = state.GetTimestamp()
	msg.RequestHash = requestHash

	return msg
}
Exemple #22
0
// LatestDirBlockLocator returns a block locator for the latest known tip of the
// main (best) chain.
func LatestDirBlockLocator(state interfaces.IState) (BlockLocator, error) {
	latestDirBlockHash := state.GetCurrentDirectoryBlock().GetHash() //, _, _ := db.FetchBlockHeightCache()

	if latestDirBlockHash == nil {
		latestDirBlockHash = NewZeroHash() //zeroHash
	}

	// The best chain is set, so use its hash.
	return DirBlockLocatorFromHash(latestDirBlockHash, state), nil
}
func NewMissingMsgResponse(state interfaces.IState, msgResponse interfaces.IMsg, ackResponse interfaces.IMsg) interfaces.IMsg {

	msg := new(MissingMsgResponse)

	msg.Peer2Peer = true // Always a peer2peer request.
	msg.Timestamp = state.GetTimestamp()
	msg.MsgResponse = msgResponse
	msg.AckResponse = ackResponse

	return msg
}
Exemple #24
0
func Follower(state interfaces.IState) {

	for {
		msg := <-state.FollowerInMsgQueue()
		if state.PrintType(msg.Type()) {
			log.Printf("%20s %s\n", "Follower:", msg.String())
		}
		msg.FollowerExecute(state)
	}

}
func (m *FactoidTransaction) Process(state interfaces.IState) {

	if m.processed {
		return
	}
	m.processed = true

	// We can only get a Factoid Transaction once.  Add it, and remove it from the lists.
	state.GetFactoidState().AddTransaction(1, m.Transaction)

}
Exemple #26
0
// Returns true if this is a message for this server to execute as
// a leader.
func (m *MsgPing) Leader(state interfaces.IState) bool {
	switch state.GetNetworkNumber() {
	case 0: // Main Network
		panic("Not implemented yet")
	case 1: // Test Network
		panic("Not implemented yet")
	case 2: // Local Network
		panic("Not implemented yet")
	default:
		panic("Not implemented yet")
	}
}
// Returns true if this is a message for this server to execute as
// a leader.
func (m *DirectoryBlockSignature) Leader(state interfaces.IState) bool {
	switch state.GetNetworkNumber() {
	case 0: // Main Network
		panic("Not implemented yet")
	case 1: // Test Network
		panic("Not implemented yet")
	case 2: // Local Network
		panic("Not implemented yet")
	default:
		panic("Not implemented yet")
	}
}
Exemple #28
0
// Try and Resend.  Return true if we should keep the message, false if we should give up.
func (m *MessageBase) Resend(s interfaces.IState) (rtn bool) {
	now := s.GetTimestamp().GetTimeMilli()
	if m.resend == 0 {
		m.resend = now
		return false
	}
	if now-m.resend > 10000 && len(s.NetworkOutMsgQueue()) < 1000 { // Resend every second
		m.resend = now
		return true
	}
	return false
}
Exemple #29
0
func SetState(state interfaces.IState) {
	wait := func() {
		ServersMutex.Lock()
		defer ServersMutex.Unlock()

		for Servers == nil && Servers[state.GetPort()] != nil {
			time.Sleep(10 * time.Millisecond)
		}
		Servers[state.GetPort()].Env["state"] = state
	}
	go wait()
}
Exemple #30
0
// Validate the message, given the state.  Three possible results:
//  < 0 -- Message is invalid.  Discard
//  0   -- Cannot tell if message is Valid
//  1   -- Message is valid
func (m *CommitEntryMsg) Validate(state interfaces.IState) int {
	if !m.validsig && !m.CommitEntry.IsValid() {
		return -1
	}
	m.validsig = true

	ebal := state.GetFactoidState().GetECBalance(*m.CommitEntry.ECPubKey)
	if int(m.CommitEntry.Credits) > int(ebal) {
		return 0
	}
	return 1
}