Exemple #1
0
func addIdentity(entry interfaces.IEBEntry, height uint32, st *State) error {
	extIDs := entry.ExternalIDs()
	// This check is here to prevent possible index out of bounds with extIDs[:6]
	if len(extIDs) != 7 {
		return errors.New("Identity Error Create Management: Invalid external ID length")
	}
	if bytes.Compare([]byte{0x00}, extIDs[0]) != 0 || // Version
		!CheckExternalIDsLength(extIDs[:6], []int{1, 14, 32, 32, 32, 32}) { // Nonce
		return errors.New("Identity Error Create Identity Chain: Invalid external ID length")
	}

	chainID := entry.GetChainID()

	IdentityIndex := st.isIdentityChain(chainID)

	if IdentityIndex == -1 {
		IdentityIndex = st.CreateBlankFactomIdentity(chainID)
	}
	h := primitives.NewHash(extIDs[2])
	st.Identities[IdentityIndex].Key1 = h
	h = primitives.NewHash(extIDs[3])
	st.Identities[IdentityIndex].Key2 = h
	h = primitives.NewHash(extIDs[4])
	st.Identities[IdentityIndex].Key3 = h
	h = primitives.NewHash(extIDs[5])
	st.Identities[IdentityIndex].Key4 = h
	st.Identities[IdentityIndex].IdentityCreated = height
	return nil
}
func TestMarshalUnmarshalServerFault(t *testing.T) {
	ts := primitives.NewTimestampNow()
	vmIndex := int(*ts) % 10
	sf := NewServerFault(primitives.NewHash([]byte("a test")), primitives.NewHash([]byte("a test2")), vmIndex, 10, 100, 0, ts)
	hex, err := sf.MarshalBinary()
	if err != nil {
		t.Error(err)
	}
	t.Logf("Marshalled - %x", hex)

	sf2, err := UnmarshalMessage(hex)
	if err != nil {
		t.Error(err)
	}
	str := sf2.String()
	t.Logf("str - %v", str)

	if sf2.Type() != constants.FED_SERVER_FAULT_MSG {
		t.Errorf("Invalid message type unmarshalled - got %v, expected %v", sf2.Type(), constants.FED_SERVER_FAULT_MSG)
	}

	hex2, err := sf2.(*ServerFault).MarshalBinary()
	if err != nil {
		t.Error(err)
	}
	if len(hex) != len(hex2) {
		t.Error("Hexes aren't of identical length")
	}
	for i := range hex {
		if hex[i] != hex2[i] {
			t.Error("Hexes do not match")
		}
	}
}
Exemple #3
0
func NextECBlock(prev interfaces.IEntryCreditBlock) (interfaces.IEntryCreditBlock, error) {
	e := NewECBlock()

	// Handle the really unusual case of the first block.
	if prev == nil {
		e.GetHeader().SetPrevHeaderHash(primitives.NewHash(constants.ZERO_HASH))
		e.GetHeader().SetPrevFullHash(primitives.NewHash(constants.ZERO_HASH))
		e.GetHeader().SetDBHeight(0)
	} else {
		v, err := prev.HeaderHash()
		if err != nil {
			return nil, err
		}
		e.GetHeader().SetPrevHeaderHash(v)

		v, err = prev.GetFullHash()
		if err != nil {
			return nil, err
		}
		e.GetHeader().SetPrevFullHash(v)

		e.GetHeader().SetDBHeight(prev.GetHeader().GetDBHeight() + 1)
	}
	if err := e.(*ECBlock).BuildHeader(); err != nil {
		return nil, err
	}

	return e, nil
}
Exemple #4
0
func (m *EOM) UnmarshalBinaryData(data []byte) (newData []byte, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Error unmarshalling EOM message: %v", r)
		}
	}()
	newData = data
	if newData[0] != m.Type() {
		return nil, fmt.Errorf("Invalid Message type")
	}
	newData = newData[1:]

	m.Timestamp = new(primitives.Timestamp)
	newData, err = m.Timestamp.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}

	m.ChainID = primitives.NewHash(constants.ZERO_HASH)
	newData, err = m.ChainID.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}

	m.Minute, newData = newData[0], newData[1:]

	if m.Minute < 0 || m.Minute >= 10 {
		return nil, fmt.Errorf("Minute number is out of range")
	}

	m.VMIndex = int(newData[0])
	newData = newData[1:]
	m.FactoidVM = uint8(newData[0]) == 1
	newData = newData[1:]

	m.DBHeight, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]
	m.SysHeight, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]

	m.SysHash = primitives.NewHash(constants.ZERO_HASH)
	newData, err = m.SysHash.UnmarshalBinaryData(newData)

	if len(newData) > 0 {
		sig := new(primitives.Signature)
		newData, err = sig.UnmarshalBinaryData(newData)
		if err != nil {
			return nil, err
		}
		m.Signature = sig
	}

	return data, nil
}
func TestThatFullAndFaultCoreHashesMatch(t *testing.T) {
	ts := primitives.NewTimestampNow()
	vmIndex := int(*ts) % 10

	sf := NewServerFault(primitives.NewHash([]byte("a test")), primitives.NewHash([]byte("a test2")), vmIndex, 10, 100, 0, ts)

	sl := coupleOfSigs(t)

	fsf := NewFullServerFault(nil, sf, sl, 0)

	if !sf.GetCoreHash().IsSameAs(fsf.GetCoreHash()) {
		t.Error("CoreHashes do not match between FullServerFault and ServerFault")
	}
}
Exemple #6
0
func (m *MissingMsg) MarshalBinary() ([]byte, error) {
	var buf primitives.Buffer

	binary.Write(&buf, binary.BigEndian, m.Type())

	t := m.GetTimestamp()
	data, err := t.MarshalBinary()
	if err != nil {
		return nil, err
	}
	buf.Write(data)

	if m.Asking == nil {
		m.Asking = primitives.NewHash(constants.ZERO_HASH)
	}
	data, err = m.Asking.MarshalBinary()
	if err != nil {
		return nil, err
	}
	buf.Write(data)

	buf.WriteByte(uint8(m.VMIndex))
	binary.Write(&buf, binary.BigEndian, m.DBHeight)
	binary.Write(&buf, binary.BigEndian, m.SystemHeight)

	binary.Write(&buf, binary.BigEndian, uint32(len(m.ProcessListHeight)))
	for _, h := range m.ProcessListHeight {
		binary.Write(&buf, binary.BigEndian, h)
	}

	bb := buf.DeepCopyBytes()

	return bb, nil
}
Exemple #7
0
func (m *EOM) MarshalBinary() (data []byte, err error) {
	var buf primitives.Buffer
	resp, err := m.MarshalForSignature()
	if err != nil {
		return nil, err
	}
	buf.Write(resp)

	binary.Write(&buf, binary.BigEndian, m.DBHeight)
	binary.Write(&buf, binary.BigEndian, m.SysHeight)

	if m.SysHash == nil {
		m.SysHash = primitives.NewHash(constants.ZERO_HASH)
	}
	if d, err := m.SysHash.MarshalBinary(); err != nil {
		return nil, err
	} else {
		buf.Write(d)
	}

	sig := m.GetSignature()
	if sig != nil {
		sigBytes, err := sig.MarshalBinary()
		if err != nil {
			return nil, err
		}
		buf.Write(sigBytes)
	}
	return buf.DeepCopyBytes(), nil
}
Exemple #8
0
func NewRepeatingHash(b byte) interfaces.IHash {
	tmp := make([]byte, constants.HASH_LENGTH)
	for i := range tmp {
		tmp[i] = b
	}
	return primitives.NewHash(tmp)
}
Exemple #9
0
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the MsgAck interface implementation.
func (msg *MsgAck) BtcDecode(r io.Reader, pver uint32) error {
	newData, err := ioutil.ReadAll(r)
	if err != nil {
		return fmt.Errorf("MsgAck.BtcDecode reader is invalid")
	}

	if len(newData) != 169 {
		return fmt.Errorf("MsgAck.BtcDecode reader does not have right length: ", len(newData))
	}

	msg.Height, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]

	msg.ChainID = new(primitives.Hash)
	newData, _ = msg.ChainID.UnmarshalBinaryData(newData)

	msg.Index, newData = binary.BigEndian.Uint32(newData[0:4]), newData[4:]

	msg.Typ, newData = newData[0], newData[1:]

	msg.Affirmation = primitives.NewHash(newData[0:32])
	newData = newData[32:]

	copy(msg.SerialHash[:], newData[0:32])
	newData = newData[32:]

	copy(msg.Signature[:], newData[0:63])

	return nil
}
Exemple #10
0
func (m *MissingData) UnmarshalBinaryData(data []byte) (newData []byte, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Error unmarshalling: %v", r)
		}
	}()
	newData = data
	if newData[0] != m.Type() {
		return nil, fmt.Errorf("Invalid Message type")
	}
	newData = newData[1:]

	m.Timestamp = new(primitives.Timestamp)
	newData, err = m.Timestamp.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}

	m.RequestHash = primitives.NewHash(constants.ZERO_HASH)
	newData, err = m.RequestHash.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}

	m.Peer2Peer = true // Always a peer2peer request.

	return data, nil
}
Exemple #11
0
func registerIdentityAsServer(entry interfaces.IEBEntry, height uint32, st *State) error {
	extIDs := entry.ExternalIDs()
	if len(extIDs) == 0 {
		return errors.New("Identity Error Register Identity: Invalid external ID length")
	}
	if bytes.Compare([]byte{0x00}, extIDs[0]) != 0 || // Version
		!CheckExternalIDsLength(extIDs, []int{1, 26, 32, 33, 64}) { // Signiture
		return errors.New("Identity Error Register Identity: Invalid external ID length")
	}
	chainID := entry.GetChainID()
	IdentityIndex := st.isIdentityChain(chainID)
	if IdentityIndex == -1 {
		IdentityIndex = st.CreateBlankFactomIdentity(chainID)
	}

	sigmsg, err := AppendExtIDs(extIDs, 0, 2)
	if err != nil {
		return err
	} else {
		// Verify Signature
		idKey := st.Identities[IdentityIndex].Key1
		if CheckSig(idKey, extIDs[3][1:33], sigmsg, extIDs[4]) {
			st.Identities[IdentityIndex].ManagementRegistered = height
			st.Identities[IdentityIndex].ManagementChainID = primitives.NewHash(extIDs[2][:32])
		} else {
			return errors.New("New Management Chain Register for identity [" + chainID.String()[:10] + "] is invalid. Bad signiture")
		}

	}
	return nil
}
Exemple #12
0
func registerFactomIdentity(entry interfaces.IEBEntry, chainID interfaces.IHash, height uint32, st *State) error {
	extIDs := entry.ExternalIDs()
	if len(extIDs) == 0 {
		return errors.New("Identity Error Register Identity: Invalid external ID length")
	}
	if bytes.Compare([]byte{0x00}, extIDs[0]) != 0 || // Version
		!CheckExternalIDsLength(extIDs, []int{1, 24, 32, 33, 64}) { // Signiture
		return errors.New("Identity Error Register Identity: Invalid external ID length")
	}

	// find the Identity index from the chain id in the external id.  add this chainID as the management id
	idChain := primitives.NewHash(extIDs[2])
	IdentityIndex := st.isIdentityChain(idChain)
	if IdentityIndex == -1 {
		IdentityIndex = st.CreateBlankFactomIdentity(idChain)
	}

	sigmsg, err := AppendExtIDs(extIDs, 0, 2)
	if err != nil {
		return err
	} else {
		// Verify Signature
		idKey := st.Identities[IdentityIndex].Key1
		if CheckSig(idKey, extIDs[3][1:33], sigmsg, extIDs[4]) {
			st.Identities[IdentityIndex].ManagementRegistered = height
		} else {
			return errors.New("New Management Chain Register for identity [" + chainID.String()[:10] + "] is invalid. Bad signiture")
		}

	}
	st.Identities[IdentityIndex].IdentityRegistered = height

	return nil
}
func getEntry(hash string) *EntryHolder {
	entryHash, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}
	dbase := StatePointer.GetAndLockDB()
	entry, err := dbase.FetchEntry(entryHash)
	StatePointer.UnlockDB()

	if err != nil {
		return nil
	}
	if entry == nil {
		return nil
	}

	holder := new(EntryHolder)
	holder.Hash = hash
	holder.ChainID = entry.GetChainID().String()
	max := byte(0x80)
	for _, data := range entry.ExternalIDs() {
		hexString := false
		for _, bytes := range data {
			if bytes > max {
				hexString = true
				break
			}
		}
		if hexString {
			str := hex.EncodeToString(data)
			holder.ExtIDs = append(holder.ExtIDs[:], "<span id='encoding'><a>Hex  : </a></span><span id='data'>"+htemp.HTMLEscaper(str)+"</span>")
		} else {
			str := string(data)
			holder.ExtIDs = append(holder.ExtIDs[:], "<span id='encoding'><a>Ascii: </a></span><span id='data'>"+htemp.HTMLEscaper(str)+"</span>")
		}
	}
	holder.Version = 0
	holder.Height = fmt.Sprintf("%d", entry.GetDatabaseHeight())
	holder.ContentLength = len(entry.GetContent())
	data := sha256.Sum256(entry.GetContent())
	content := string(entry.GetContent())
	holder.Content = htemp.HTMLEscaper(content)
	if bytes, err := entry.MarshalBinary(); err != nil {
		holder.ECCost = "Error"
	} else {
		if eccost, err := util.EntryCost(bytes); err != nil {
			holder.ECCost = "Error"
		} else {
			holder.ECCost = fmt.Sprintf("%d", eccost)
		}
	}

	//holder.Content = string(entry.GetContent())
	holder.ContentHash = primitives.NewHash(data[:]).String()
	return holder
}
Exemple #14
0
func (s *State) CreateDBlock() (b interfaces.IDirectoryBlock, err error) {
	prev := s.GetCurrentDirectoryBlock()

	b = new(directoryBlock.DirectoryBlock)

	b.SetHeader(new(directoryBlock.DBlockHeader))
	b.GetHeader().SetVersion(constants.VERSION_0)

	if prev == nil {
		b.GetHeader().SetPrevLedgerKeyMR(primitives.NewZeroHash())
		b.GetHeader().SetPrevKeyMR(primitives.NewZeroHash())
		b.GetHeader().SetDBHeight(0)
		eb, _ := entryCreditBlock.NextECBlock(nil)
		s.EntryCreditBlock = eb
	} else {
		bodyMR, err := prev.BuildBodyMR()
		if err != nil {
			return nil, err
		}
		prev.GetHeader().SetBodyMR(bodyMR)

		prevLedgerKeyMR := prev.GetHash()
		if prevLedgerKeyMR == nil {
			return nil, errors.New("prevLedgerKeyMR is nil")
		}
		b.GetHeader().SetPrevLedgerKeyMR(prevLedgerKeyMR)
		b.GetHeader().SetPrevKeyMR(prev.GetKeyMR())
		b.GetHeader().SetDBHeight(prev.GetHeader().GetDBHeight() + 1)
		eb, _ := entryCreditBlock.NextECBlock(s.EntryCreditBlock)
		s.EntryCreditBlock = eb
	}

	b.SetDBEntries(make([]interfaces.IDBEntry, 0))

	s.CurrentAdminBlock = s.NewAdminBlock()

	b.AddEntry(primitives.NewHash(constants.ADMIN_CHAINID), primitives.NewZeroHash())
	b.AddEntry(primitives.NewHash(constants.EC_CHAINID), primitives.NewZeroHash())
	b.AddEntry(primitives.NewHash(constants.FACTOID_CHAINID), primitives.NewZeroHash())

	return b, err
}
Exemple #15
0
func (db *Overlay) FetchECBlockHead() (interfaces.IEntryCreditBlock, error) {
	blk := entryCreditBlock.NewECBlock()
	block, err := db.FetchChainHeadByChainID([]byte{byte(ENTRYCREDITBLOCK)}, primitives.NewHash(blk.GetChainID()), blk)
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, nil
	}
	return block.(interfaces.IEntryCreditBlock), nil
}
Exemple #16
0
func (db *Overlay) FetchFactoidBlockHead() (interfaces.IFBlock, error) {
	blk := new(block.FBlock)
	block, err := db.FetchChainHeadByChainID([]byte{byte(FACTOIDBLOCK)}, primitives.NewHash(blk.GetChainID()), blk)
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, nil
	}
	return block.(interfaces.IFBlock), nil
}
Exemple #17
0
func (db *Overlay) FetchDirectoryBlockHead() (interfaces.IDirectoryBlock, error) {
	blk := new(directoryBlock.DirectoryBlock)
	block, err := db.FetchChainHeadByChainID(DIRECTORYBLOCK, primitives.NewHash(blk.GetChainID().Bytes()), blk)
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, nil
	}
	return block.(interfaces.IDirectoryBlock), nil
}
Exemple #18
0
func (db *Overlay) FetchABlockHead() (interfaces.IAdminBlock, error) {
	blk := adminBlock.NewAdminBlock()
	block, err := db.FetchChainHeadByChainID([]byte{byte(ADMINBLOCK)}, primitives.NewHash(blk.GetChainID()), blk)
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, nil
	}
	return block.(interfaces.IAdminBlock), nil
}
func NewDirectoryBlock(prev interfaces.IDirectoryBlock) interfaces.IDirectoryBlock {
	newdb := new(DirectoryBlock)

	newdb.Header = new(DBlockHeader)
	newdb.Header.SetVersion(constants.VERSION_0)

	if prev != nil {
		newdb.GetHeader().SetPrevFullHash(prev.GetFullHash())
		newdb.GetHeader().SetPrevKeyMR(prev.GetKeyMR())
		newdb.GetHeader().SetDBHeight(prev.GetHeader().GetDBHeight() + 1)
	} else {
		newdb.Header.SetPrevFullHash(primitives.NewZeroHash())
		newdb.Header.SetPrevKeyMR(primitives.NewZeroHash())
		newdb.GetHeader().SetDBHeight(0)
	}

	newdb.SetDBEntries(make([]interfaces.IDBEntry, 0))

	newdb.AddEntry(primitives.NewHash(constants.ADMIN_CHAINID), primitives.NewZeroHash())
	newdb.AddEntry(primitives.NewHash(constants.EC_CHAINID), primitives.NewZeroHash())
	newdb.AddEntry(primitives.NewHash(constants.FACTOID_CHAINID), primitives.NewZeroHash())

	return newdb
}
Exemple #20
0
func (m *DataResponse) UnmarshalBinaryData(data []byte) (newData []byte, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Error unmarshalling: %v", r)
		}
	}()
	newData = data
	if newData[0] != m.Type() {
		return nil, fmt.Errorf("Invalid Message type")
	}
	newData = newData[1:]

	m.Timestamp = new(primitives.Timestamp)
	newData, err = m.Timestamp.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}

	m.DataType = int(newData[0])
	newData = newData[1:]

	m.DataHash = primitives.NewHash(constants.ZERO_HASH)
	newData, err = m.DataHash.UnmarshalBinaryData(newData)
	if err != nil {
		return nil, err
	}
	switch m.DataType {
	case 0:
		entryAttempt, err := attemptEntryUnmarshal(newData)
		if err != nil {
			return nil, err
		} else {
			m.DataObject = entryAttempt
		}
	case 1:
		eblockAttempt, err := attemptEBlockUnmarshal(newData)
		if err != nil {
			return nil, err
		} else {
			m.DataObject = eblockAttempt
		}
	default:
		return nil, fmt.Errorf("DataResponse's DataType not supported for unmarshalling yet")
	}

	m.Peer2Peer = true // Always a peer2peer request.
	return data, nil
}
func (s *State) FollowerExecuteDBState(msg interfaces.IMsg) {
	dbstatemsg, _ := msg.(*messages.DBStateMsg)

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

	if s.GetHighestCompletedBlock() > dbheight {
		return
	}
	pdbstate := s.DBStates.Get(int(dbheight - 1))

	switch pdbstate.ValidNext(s, dbstatemsg.DirectoryBlock) {
	case 0:
		k := fmt.Sprint("dbstate", dbheight-1)
		key := primitives.NewHash([]byte(k))
		s.Holding[key.Fixed()] = msg
		return
	case -1:
		// Kill the previous DBState, because it could be bad.
		if dbheight > s.DBStates.Base && len(s.DBStates.DBStates) > int(dbheight-s.DBStates.Base) {
			s.DBStates.DBStates[dbheight-s.DBStates.Base] = nil
			s.DBStateFailsCnt++
			s.networkInvalidMsgQueue <- msg
		}
		return
	}

	s.DBStates.LastTime = s.GetTimestamp()
	dbstate := s.AddDBState(false,
		dbstatemsg.DirectoryBlock,
		dbstatemsg.AdminBlock,
		dbstatemsg.FactoidBlock,
		dbstatemsg.EntryCreditBlock,
		dbstatemsg.EBlocks,
		dbstatemsg.Entries)
	if dbstate == nil {
		s.DBStateFailsCnt++
	} else {
		if dbstatemsg.IsInDB == false {
			dbstate.ReadyToSave = true
			dbstate.Locked = false
		} else {
			dbstate.Saved = true
			dbstate.isNew = false
			dbstate.Locked = false
		}
	}
}
Exemple #22
0
func (s *State) NewAdminBlockHeader() interfaces.IABlockHeader {
	header := new(adminBlock.ABlockHeader)
	header.DBHeight = s.GetDBHeight()
	if s.GetCurrentAdminBlock() == nil {
		header.PrevLedgerKeyMR = primitives.NewHash(constants.ZERO_HASH)
	} else {
		keymr, err := s.GetCurrentAdminBlock().LedgerKeyMR()
		if err != nil {
			panic(err.Error())
		}
		header.PrevLedgerKeyMR = keymr
	}
	header.HeaderExpansionSize = 0
	header.HeaderExpansionArea = make([]byte, 0)
	header.MessageCount = 0
	header.BodySize = 0
	return header
}
func CreateTestEntryBlockForFER(p interfaces.IEntryBlock, height uint32) (*entryBlock.EBlock, []*entryBlock.Entry) {
	prev, ok := p.(*entryBlock.EBlock)
	if ok == false {
		prev = nil
	}

	e := entryBlock.NewEBlock()
	entries := []*entryBlock.Entry{}

	if prev != nil {
		keyMR, err := prev.KeyMR()
		if err != nil {
			panic(err)
		}

		e.Header.SetPrevKeyMR(keyMR)
		hash, err := prev.Hash()
		if err != nil {
			panic(err)
		}
		e.Header.SetPrevFullHash(hash)
		e.Header.SetDBHeight(prev.GetHeader().GetDBHeight() + 1)

		e.Header.SetChainID(prev.GetHeader().GetChainID())
		entry := CreateTestFEREntry(e.Header.GetDBHeight())
		e.AddEBEntry(entry)
		entries = append(entries, entry)
	} else {
		e.Header.SetPrevKeyMR(primitives.NewZeroHash())
		e.Header.SetDBHeight(0)
		chainId := "111111118d918a8be684e0dac725493a75862ef96d2d3f43f84b26969329bf03"
		hexBytes, _ := hex.DecodeString(chainId)
		chainIdHash := primitives.NewHash(hexBytes)
		e.Header.SetChainID(chainIdHash)

		entry := CreateFirstTestEntry()
		e.AddEBEntry(entry)
		entries = append(entries, entry)
	}

	return e, entries
}
func (b *DirectoryBlock) BuildKeyMerkleRoot() (keyMR interfaces.IHash, err error) {
	// Create the Entry Block Key Merkle Root from the hash of Header and the Body Merkle Root

	hashes := make([]interfaces.IHash, 0, 2)
	bodyKeyMR := b.BodyKeyMR() //This needs to be called first to build the header properly!!
	headerHash, err := b.HeaderHash()
	if err != nil {
		return nil, err
	}
	hashes = append(hashes, headerHash)
	hashes = append(hashes, bodyKeyMR)
	merkle := primitives.BuildMerkleTreeStore(hashes)
	keyMR = merkle[len(merkle)-1] // MerkleRoot is not marshalized in Dir Block

	b.KeyMR = keyMR

	b.GetFullHash() // Create the Full Hash when we create the keyMR

	return primitives.NewHash(keyMR.Bytes()), nil
}
func (e *DBEntry) MarshalBinary() (data []byte, err error) {
	var buf bytes.Buffer

	data, err = e.ChainID.MarshalBinary()
	if err != nil {
		return
	}
	buf.Write(data)

	if e.KeyMR == nil {
		data, err = primitives.NewHash(constants.ZERO_HASH).MarshalBinary()
	} else {
		data, err = e.KeyMR.MarshalBinary()
	}
	if err != nil {
		return
	}
	buf.Write(data)

	return buf.Bytes(), nil
}
// Create a new DB Signature Entry
func NewAddFederatedServer(identityChainID interfaces.IHash, dbheight uint32) (e *AddFederatedServer) {
	e = new(AddFederatedServer)
	e.DBHeight = dbheight
	e.IdentityChainID = primitives.NewHash(identityChainID.Bytes())
	return
}
func (c *DirectoryBlock) GetChainID() interfaces.IHash {
	return primitives.NewHash(constants.D_CHAINID)
}
Exemple #28
0
// Control Panel shows the last 100 entry and factoid transactions. This will look into the past if we do not
// currently have 100 of each transaction type. A checkpoint is set each time we check a new height, so we will
// not check a directory block in the past twice.
func getPastEntries(last interfaces.IDirectoryBlock, eNeeded int, fNeeded int) {
	height := last.GetHeader().GetDBHeight()

	next := last.GetHeader().GetPrevKeyMR()
	zero := primitives.NewZeroHash()

	newCheckpoint := height

	for height > RecentTransactions.LastHeightChecked && (eNeeded > 0 || fNeeded > 0) {
		if next.IsSameAs(zero) {
			break
		}
		dbase := StatePointer.GetAndLockDB()
		dblk, err := dbase.FetchDBlock(next)
		StatePointer.UnlockDB()
		if err != nil || dblk == nil {
			break
		}
		height = dblk.GetHeader().GetDBHeight()
		ents := dblk.GetDBEntries()
		if len(ents) > 3 && eNeeded > 0 {
			for _, eblock := range ents[3:] {
				dbase := StatePointer.GetAndLockDB()
				eblk, err := dbase.FetchEBlock(eblock.GetKeyMR())
				StatePointer.UnlockDB()
				if err != nil || eblk == nil {
					break
				}
				for _, hash := range eblk.GetEntryHashes() {
					if RecentTransactions.ContainsEntry(hash) {
						continue
					}
					e := getEntry(hash.String())
					if e != nil && eNeeded > 0 {
						eNeeded--
						RecentTransactions.Entries = append(RecentTransactions.Entries, *e)
						//RecentTransactions.Entries = append([]EntryHolder{*e}, RecentTransactions.Entries...)
					}
				}
			}
		}
		if fNeeded > 0 {
			fChain := primitives.NewHash(constants.FACTOID_CHAINID)
			for _, entry := range ents {
				if entry.GetChainID().IsSameAs(fChain) {
					dbase := StatePointer.GetAndLockDB()
					fblk, err := dbase.FetchFBlock(entry.GetKeyMR())
					StatePointer.UnlockDB()
					if err != nil || fblk == nil {
						break
					}
					transList := fblk.GetTransactions()
					for _, trans := range transList {
						if RecentTransactions.ContainsTrans(trans.GetSigHash()) {
							continue
						}
						if trans != nil {
							input, err := trans.TotalInputs()
							if err != nil || input == 0 {
								continue
							}
							totalInputs := len(trans.GetInputs())
							totalOutputs := len(trans.GetECOutputs())
							totalOutputs = totalOutputs + len(trans.GetOutputs())
							inputStr := fmt.Sprintf("%f", float64(input)/1e8)
							fNeeded--
							RecentTransactions.FactoidTransactions = append(RecentTransactions.FactoidTransactions, struct {
								TxID         string
								Hash         string
								TotalInput   string
								Status       string
								TotalInputs  int
								TotalOutputs int
							}{trans.GetSigHash().String(), trans.GetHash().String(), inputStr, "Confirmed", totalInputs, totalOutputs})
						}
					}
				}
			}
		}
		next = dblk.GetHeader().GetPrevKeyMR()
	}

	DisplayStateMutex.Lock()
	if newCheckpoint < DisplayState.CurrentEBDBHeight && newCheckpoint > RecentTransactions.LastHeightChecked {
		RecentTransactions.LastHeightChecked = newCheckpoint
	}
	DisplayStateMutex.Unlock()
}
func (b *ABlockHeader) GetAdminChainID() interfaces.IHash {
	return primitives.NewHash(constants.ADMIN_CHAINID)
}
Exemple #30
0
package state

import (
	"fmt"
	"github.com/FactomProject/factomd/common/constants"
	"github.com/FactomProject/factomd/common/entryCreditBlock"
	"github.com/FactomProject/factomd/common/factoid/block"
	"github.com/FactomProject/factomd/common/factoid/block/coinbase"
	"github.com/FactomProject/factomd/common/interfaces"
	"github.com/FactomProject/factomd/common/primitives"
	"runtime/debug"
)

var _ = debug.PrintStack

var FACTOID_CHAINID_HASH = primitives.NewHash(constants.FACTOID_CHAINID)

type FactoidState struct {
	State interfaces.IState

	CurrentBlock interfaces.IFBlock
	Wallet       interfaces.ISCWallet

	ValidationService chan ValidationMsg
}

var _ interfaces.IFactoidState = (*FactoidState)(nil)

func (fs *FactoidState) EndOfPeriod(period int) {
	fs.GetCurrentBlock().EndOfPeriod(period)
}