Exemplo n.º 1
0
func listen() {
	prtone := false
	for {
		msg, err := p2pProxy.Recieve()
		if err != nil || msg == nil {
			if !prtone {
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			prtone = true
			time.Sleep(1 * time.Millisecond)
			continue
		}
		time.Sleep(1 * time.Millisecond)

		if old[msg.GetHash().Fixed()] == nil {
			prtone = false
			old[msg.GetHash().Fixed()] = msg
			bounce, ok := msg.(*messages.Bounce)
			if ok && len(bounce.Stamps) < 100 {
				bounce.Stamps = append(bounce.Stamps, primitives.NewTimestampNow())
				p2pProxy.Send(msg)
				fmt.Println(msg.String())
			}
			bounces++
		} else {
			oldcnt++
		}
	}
}
Exemplo n.º 2
0
func newAddServer() *AddServerMsg {
	addserv := new(AddServerMsg)
	addserv.Timestamp = primitives.NewTimestampNow()
	addserv.ServerChainID = primitives.Sha([]byte("FNode0"))
	addserv.ServerType = 0
	return addserv
}
Exemplo n.º 3
0
func (m *BounceReply) String() string {
	// bbbb Origin: 2016-09-05 12:26:20.426954586 -0500 CDT left BounceReply Start:             2016-09-05 12:26:05 Hops:     1 Size:    43 Last Hop Took 14.955 Average Hop: 14.955
	now := time.Now()
	t := fmt.Sprintf("%2d:%2d:%2d.%03d", now.Hour(), now.Minute(), now.Second(), now.Nanosecond()/1000000)
	mill := m.Timestamp.GetTimeMilli()
	mills := mill % 1000
	mill = mill / 1000
	secs := mill % 60
	mill = mill / 60
	mins := mill % 60
	mill = mill / 60
	hrs := mill % 24
	t2 := fmt.Sprintf("%2d:%2d:%2d.%03d", hrs, mins, secs, mills)
	str := fmt.Sprintf("Origin: %12s  %10s-%03d-%03d BounceReply Start: %12s Hops: %5d Size: %5d ",
		t,
		strings.TrimSpace(m.Name),
		m.Number,
		len(m.Stamps),
		t2,
		len(m.Stamps), m.SizeOf())

	elapse := primitives.NewTimestampNow().GetTimeMilli() - m.Stamps[len(m.Stamps)-1].GetTimeMilli()

	str = str + fmt.Sprintf("Last Hop Took %d.%03d", elapse/1000, elapse%1000)
	return str
}
Exemplo n.º 4
0
func (m *Bounce) String() string {
	// bbbb Origin: 2016-09-05 12:26:20.426954586 -0500 CDT left Bounce Start:             2016-09-05 12:26:05 Hops:     1 Size:    43 Last Hop Took 14.955 Average Hop: 14.955
	now := time.Now()
	t := fmt.Sprintf("%2d:%02d:%02d.%03d", now.Hour(), now.Minute(), now.Second(), now.Nanosecond()/1000000)
	mill := m.Timestamp.GetTimeMilli()
	mills := mill % 1000
	mill = mill / 1000
	secs := mill % 60
	mill = mill / 60
	mins := mill % 60
	mill = mill / 60
	hrs := mill % 24
	t2 := fmt.Sprintf("%2d:%2d:%2d.%03d", hrs, mins, secs, mills)
	str := fmt.Sprintf("Origin: %12s  %30s-%03d-%03d Bounce Start: %12s Hops: %5d Size: %5d ",
		t,
		strings.TrimSpace(m.Name),
		m.Number,
		len(m.Stamps),
		t2,
		len(m.Stamps), m.SizeOf())
	var sum int64
	for i := 0; i < len(m.Stamps)-1; i++ {
		sum += m.Stamps[i+1].GetTimeMilli() - m.Stamps[i].GetTimeMilli()
	}
	elapse := primitives.NewTimestampNow().GetTimeMilli() - m.Stamps[len(m.Stamps)-1].GetTimeMilli()
	sum += elapse
	sign := " "
	if sum < 0 {
		sign = "-"
		sum = sum * -1
	}
	avg := sum / (int64(len(m.Stamps)))
	str = str + fmt.Sprintf("Last Hop Took %3d.%03d Average Hop: %s%3d.%03d Hash: %x", elapse/1000, elapse%1000, sign, avg/1000, avg%1000, m.GetHash().Bytes()[:4])
	return str
}
Exemplo n.º 5
0
func (a *Anchor) checkMissingDirBlockInfo() {
	anchorLog.Debug("checkMissingDirBlockInfo for those unsaved DirBlocks in database")
	dblocks, _ := a.db.FetchAllDBlocks()
	dirBlockInfos, _ := a.db.FetchAllDirBlockInfos() //FetchAllDirBlockInfos()
	for _, dblock := range dblocks {
		var found = false
		for i, dbinfo := range dirBlockInfos {
			if dbinfo.GetDatabaseHeight() == dblock.GetDatabaseHeight() {
				dirBlockInfos = append(dirBlockInfos[:i], dirBlockInfos[i+1:]...)
				found = true
				break
			}
		}
		if !found {
			if dblock.GetKeyMR() == nil || bytes.Compare(dblock.GetKeyMR().Bytes(), primitives.NewZeroHash().Bytes()) == 0 {
				dblock.BuildKeyMerkleRoot()
			}
			dirBlockInfo := dbInfo.NewDirBlockInfoFromDirBlock(dblock)
			dirBlockInfo.SetTimestamp(primitives.NewTimestampNow())
			anchorLog.Debug("add missing dirBlockInfo to map: ", spew.Sdump(dirBlockInfo))
			a.db.SaveDirBlockInfo(dirBlockInfo)
			a.dirBlockInfoSlice = append(a.dirBlockInfoSlice, dirBlockInfo)
		}
	}
}
Exemplo n.º 6
0
func newAck() *Ack {
	ack := new(Ack)
	ack.Timestamp = primitives.NewTimestampNow()
	hash, err := primitives.NewShaHashFromStr("cbd3d09db6defdc25dfc7d57f3479b339a077183cd67022e6d1ef6c041522b40")
	if err != nil {
		panic(err)
	}
	ack.MessageHash = hash

	hash, err = primitives.NewShaHashFromStr("bbd3d09db6defdc25dfc7d57f3479b339a077183cd67022e6d1ef6c041522b40")
	if err != nil {
		panic(err)
	}
	ack.MessageHash = hash

	ack.DBHeight = 123
	ack.Height = 456

	hash, err = primitives.NewShaHashFromStr("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	if err != nil {
		panic(err)
	}
	ack.SerialHash = hash

	hash, err = primitives.NewShaHashFromStr("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
	if err != nil {
		panic(err)
	}
	ack.LeaderChainID = hash

	return ack
}
Exemplo n.º 7
0
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")
		}
	}
}
Exemplo n.º 8
0
func newDBStateMissing() *DBStateMissing {
	msg := new(DBStateMissing)
	msg.Timestamp = primitives.NewTimestampNow()

	msg.DBHeightStart = 0x01234567
	msg.DBHeightEnd = 0x89012345

	return msg
}
Exemplo n.º 9
0
func newDataResponseEntry() *DataResponse {
	dr := new(DataResponse)
	dr.Timestamp = primitives.NewTimestampNow()
	dr.DataType = 0
	entry := testHelper.CreateFirstTestEntry()
	dr.DataObject = entry
	dr.DataHash = entry.GetHash()
	return dr
}
Exemplo n.º 10
0
func newDataResponseEntryBlock() *DataResponse {
	dr := new(DataResponse)
	dr.Timestamp = primitives.NewTimestampNow()
	dr.DataType = 1
	entry, _ := testHelper.CreateTestEntryBlock(nil)
	dr.DataObject = entry
	dr.DataHash, _ = entry.KeyMR()
	return dr
}
Exemplo n.º 11
0
func newMissingMsg() *MissingMsg {
	msg := new(MissingMsg)
	msg.Timestamp = primitives.NewTimestampNow()
	msg.Asking = primitives.NewZeroHash()

	msg.DBHeight = 0x12345678
	msg.ProcessListHeight = append(msg.ProcessListHeight, 0x98765432)

	return msg
}
Exemplo n.º 12
0
func newChangeServerKey() *ChangeServerKeyMsg {
	addserv := new(ChangeServerKeyMsg)
	addserv.Timestamp = primitives.NewTimestampNow()
	addserv.IdentityChainID = primitives.Sha([]byte("FNode0"))
	addserv.AdminBlockChange = 0
	addserv.KeyPriority = 0
	addserv.KeyType = 0
	addserv.Key = primitives.Sha([]byte("A_Key"))
	return addserv
}
Exemplo n.º 13
0
func newMissingData() *MissingData {
	msg := new(MissingData)
	msg.Timestamp = primitives.NewTimestampNow()

	h, err := primitives.NewShaHashFromStr("deadbeef00000000000000000000000000000000000000000000000000000000")
	if err != nil {
		panic(err)
	}
	msg.RequestHash = h

	return msg
}
Exemplo n.º 14
0
func main() {
	InitNetwork()

	time.Sleep(1 * time.Second)
	fmt.Println("Starting...")

	go listen()

	for {
		bounce := new(messages.Bounce)
		bounce.Number = cntreq
		cntreq++
		bounce.Name = name
		bounce.Timestamp = primitives.NewTimestampNow()
		bounce.Stamps = append(bounce.Stamps, primitives.NewTimestampNow())
		if isp2p {
			bounce.SetPeer2Peer(true)
			p2pRequestSent++
		} else {
			broadcastSent++
		}
		p2pProxy.Send(bounce)
		SetMsg(bounce)

		if isp2p {
			fmt.Printf("netTest(%s):  ::p2p:: request sent: %d request recieved %d sent: %d received: %d\n",
				name,
				p2pRequestSent, p2pRequestReceived,
				p2pSent, p2pReceived)

		} else {
			fmt.Printf("netTest(%s):  ::: broadcast sent: %d broadcast received: %d\n",
				name,

				broadcastSent, broadcastReceived)
		}
		time.Sleep(8 * time.Second)
	}
}
Exemplo n.º 15
0
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")
	}
}
Exemplo n.º 16
0
func CreateTestDBStateList() []interfaces.IMsg {
	answer := make([]interfaces.IMsg, BlockCount)
	var prev *BlockSet = nil

	for i := 0; i < BlockCount; i++ {
		prev = CreateTestBlockSet(prev)

		timestamp := primitives.NewTimestampNow()
		timestamp.SetTime(uint64(i * 1000 * 60 * 60 * 6)) //6 hours of difference between messages

		answer[i] = messages.NewDBStateMsg(timestamp, prev.DBlock, prev.ABlock, prev.FBlock, prev.ECBlock, nil, nil)
	}
	return answer
}
Exemplo n.º 17
0
func TestServerFaultUpdateState(t *testing.T) {
	sigs := 10
	sf := new(ServerFault)

	sf.Timestamp = primitives.NewTimestampNow()
	sf.ServerID = testHelper.NewRepeatingHash(1)
	sf.AuditServerID = testHelper.NewRepeatingHash(2)

	sf.VMIndex = 0x33
	sf.DBHeight = 0x44556677
	sf.Height = 0x88990011

	core, err := sf.MarshalCore()
	if err != nil {
		t.Errorf("%v", err)
	}
	for i := 0; i < sigs; i++ {
		priv := testHelper.NewPrimitivesPrivateKey(uint64(i))
		sig := priv.Sign(core)
		sf.SignatureList.List = append(sf.SignatureList.List, sig)
	}
	sf.SignatureList.Length = uint32(len(sf.SignatureList.List))

	s := testHelper.CreateAndPopulateTestState()
	idindex := s.CreateBlankFactomIdentity(primitives.NewZeroHash())
	s.Identities[idindex].ManagementChainID = primitives.NewZeroHash()
	for i := 0; i < sigs; i++ {
		//Federated Server
		index := s.AddAuthorityFromChainID(testHelper.NewRepeatingHash(byte(i)))
		s.Authorities[index].SigningKey = *testHelper.NewPrimitivesPrivateKey(uint64(i)).Pub
		s.Authorities[index].Status = 1

		s.AddFedServer(s.GetLeaderHeight(), testHelper.NewRepeatingHash(byte(i)))

		//Audit Server
		index = s.AddAuthorityFromChainID(testHelper.NewRepeatingHash(byte(i + sigs)))
		s.Authorities[index].SigningKey = *testHelper.NewPrimitivesPrivateKey(uint64(i + sigs)).Pub
		s.Authorities[index].Status = 0

		s.AddFedServer(s.GetLeaderHeight(), testHelper.NewRepeatingHash(byte(i+sigs)))
	}

	err = sf.UpdateState(s)
	if err != nil {
		t.Errorf("%v", err)
	}

}
Exemplo n.º 18
0
func newHeartbeat() *Heartbeat {
	eom := new(Heartbeat)
	eom.Timestamp = primitives.NewTimestampNow()
	h, err := primitives.NewShaHashFromStr("deadbeef00000000000000000000000000000000000000000000000000000000")
	if err != nil {
		panic(err)
	}
	eom.DBlockHash = h
	h, err = primitives.NewShaHashFromStr("deadbeef00000000000000000000000000000000000000000000000000000000")
	if err != nil {
		panic(err)
	}
	eom.IdentityChainID = h

	return eom
}
Exemplo n.º 19
0
func (a *Anchor) doSaveDirBlockInfo(transaction *btcutil.Tx, details *btcjson.BlockDetails, dirBlockInfo *dbInfo.DirBlockInfo, replace bool) {
	if replace {
		dirBlockInfo.BTCTxHash = toHash(transaction.Sha()) // in case of tx being malleated
	}
	dirBlockInfo.BTCTxOffset = int32(details.Index)
	dirBlockInfo.BTCBlockHeight = details.Height
	btcBlockHash, _ := wire.NewShaHashFromStr(details.Hash)
	dirBlockInfo.BTCBlockHash = toHash(btcBlockHash)
	dirBlockInfo.SetTimestamp(primitives.NewTimestampNow())
	a.db.SaveDirBlockInfo(dirBlockInfo)
	anchorLog.Infof("In doSaveDirBlockInfo, dirBlockInfo:%s saved to db\n", spew.Sdump(dirBlockInfo))

	// to make factom / explorer more user friendly, instead of waiting for
	// over 2 hours to know it's anchored, we can create the anchor chain instantly
	// then change it when the btc main chain re-org happens.
	a.saveToAnchorChain(dirBlockInfo)
}
Exemplo n.º 20
0
func (s *State) SendHeartBeat() {
	dbstate := s.DBStates.Get(int(s.LLeaderHeight - 1))
	if dbstate == nil {
		return
	}
	for _, auditServer := range s.GetAuditServers(s.LLeaderHeight) {
		if auditServer.GetChainID().IsSameAs(s.IdentityChainID) {
			hb := new(messages.Heartbeat)
			hb.Timestamp = primitives.NewTimestampNow()
			hb.SecretNumber = s.GetSalt(hb.Timestamp)
			hb.DBlockHash = dbstate.DBHash
			hb.IdentityChainID = s.IdentityChainID
			hb.Sign(s.GetServerPrivateKey())
			hb.SendOut(s, hb)
		}
	}
}
Exemplo n.º 21
0
func newDBStateMsg() *DBStateMsg {
	msg := new(DBStateMsg)
	msg.Timestamp = primitives.NewTimestampNow()

	set := testHelper.CreateTestBlockSet(nil)
	set = testHelper.CreateTestBlockSet(set)

	msg.DirectoryBlock = set.DBlock
	msg.AdminBlock = set.ABlock
	msg.FactoidBlock = set.FBlock
	msg.EntryCreditBlock = set.ECBlock
	msg.EBlocks = []interfaces.IEntryBlock{set.EBlock, set.AnchorEBlock}
	for _, e := range set.Entries {
		msg.Entries = append(msg.Entries, e)
	}

	return msg
}
Exemplo n.º 22
0
func main() {
	InitNetwork()

	go listen()

	for {
		if msgcnt < 10 {
			bounce := new(messages.Bounce)
			bounce.Number = int32(msgcnt)
			bounce.Name = name
			bounce.Timestamp = primitives.NewTimestampNow()
			p2pProxy.Send(bounce)
			msgcnt++
		}
		fmt.Printf("bbbb Summary: Reads: %d errs %d Writes %d errs %d Msg Sent %d Msg Received %d\n",
			p2p.Reads, p2p.ReadsErr,
			p2p.Writes, p2p.WritesErr,
			msgcnt, bounces)
		time.Sleep(20 * time.Second)
	}

}
Exemplo n.º 23
0
func (a *Anchor) checkConfirmations(dirBlockInfo *dbInfo.DirBlockInfo, index int) error {
	anchorLog.Debug("check Confirmations for btc tx: ", toShaHash(dirBlockInfo.GetBTCTxHash()).String())
	txResult, err := a.wclient.GetTransaction(toShaHash(dirBlockInfo.GetBTCTxHash()))
	if err != nil {
		anchorLog.Debugf(err.Error())
		return err
	}
	anchorLog.Debugf("GetTransactionResult: %s\n", spew.Sdump(txResult))
	if txResult.Confirmations >= int64(a.confirmationsNeeded) {
		btcBlockHash, _ := wire.NewShaHashFromStr(txResult.BlockHash)
		var rewrite = false
		// Either the call back is not recorded in case of BTCBlockHash is zero hash,
		// or bad things like re-organization of btc main chain happened
		if bytes.Compare(dirBlockInfo.BTCBlockHash.Bytes(), btcBlockHash.Bytes()) != 0 {
			anchorLog.Debugf("BTCBlockHash changed: original BTCBlockHeight=%d, original BTCBlockHash=%s, original tx offset=%d\n", dirBlockInfo.BTCBlockHeight, toShaHash(dirBlockInfo.BTCBlockHash).String(), dirBlockInfo.BTCTxOffset)
			dirBlockInfo.BTCBlockHash = toHash(btcBlockHash)
			btcBlock, err := a.wclient.GetBlockVerbose(btcBlockHash, true)
			if err != nil {
				anchorLog.Debugf(err.Error())
			}
			if btcBlock.Height > 0 {
				dirBlockInfo.BTCBlockHeight = int32(btcBlock.Height)
			}
			anchorLog.Debugf("BTCBlockHash changed: new BTCBlockHeight=%d, new BTCBlockHash=%s, btcBlockVerbose.Height=%d\n", dirBlockInfo.BTCBlockHeight, btcBlockHash.String(), btcBlock.Height)
			rewrite = true
		}
		dirBlockInfo.BTCConfirmed = true // needs confirmationsNeeded (20) to be confirmed.
		dirBlockInfo.SetTimestamp(primitives.NewTimestampNow())
		a.db.SaveDirBlockInfo(dirBlockInfo)
		a.dirBlockInfoSlice = append(a.dirBlockInfoSlice[:index], a.dirBlockInfoSlice[index+1:]...) //delete it
		anchorLog.Debugf("Fully confirmed %d times. txid=%s, dirblockInfo=%s\n", txResult.Confirmations, txResult.TxID, spew.Sdump(dirBlockInfo))
		if rewrite {
			anchorLog.Debug("rewrite to anchor chain: ", spew.Sdump(dirBlockInfo))
			a.saveToAnchorChain(dirBlockInfo)
		}
	}
	return nil
}
Exemplo n.º 24
0
func (a *Anchor) doTransaction(hash interfaces.IHash, blockHeight uint32, dirBlockInfo *dbInfo.DirBlockInfo) (*wire.ShaHash, error) {
	b := a.balances[0]
	a.balances = a.balances[1:]
	anchorLog.Info("new balances.len=", len(a.balances))

	msgtx, err := a.createRawTransaction(b, hash.Bytes(), blockHeight)
	if err != nil {
		return nil, fmt.Errorf("cannot create Raw Transaction: %s", err)
	}

	shaHash, err := a.sendRawTransaction(msgtx)
	if err != nil {
		return nil, fmt.Errorf("cannot send Raw Transaction: %s", err)
	}

	if dirBlockInfo != nil {
		dirBlockInfo.BTCTxHash = toHash(shaHash)
		dirBlockInfo.SetTimestamp(primitives.NewTimestampNow())
		a.db.SaveDirBlockInfo(dirBlockInfo)
	}

	return shaHash, nil
}
Exemplo n.º 25
0
// Checks if the timestamp is valid.  If the timestamp is too old or
// too far into the future, then we don't consider it valid.  Or if we
// have seen this hash before, then it is not valid.  To that end,
// this code remembers hashes tested in the past, and rejects the
// second submission of the same hash.
func (r *Replay) IsTSValid(mask int, hash interfaces.IHash, timestamp interfaces.Timestamp) bool {
	return r.IsTSValid_(mask, hash.Fixed(), timestamp, primitives.NewTimestampNow())
}
Exemplo n.º 26
0
func newSignatureTimeout() *SignatureTimeout {
	msg := new(SignatureTimeout)
	msg.Timestamp = primitives.NewTimestampNow()

	return msg
}
Exemplo n.º 27
0
func listen() {

	for {
		msg, err := p2pProxy.Recieve()
		if err != nil || msg == nil {
			time.Sleep(1 * time.Millisecond)
			continue
		}
		time.Sleep(1 * time.Millisecond)

		bounce, ok1 := msg.(*messages.Bounce)
		bounceReply, ok2 := msg.(*messages.BounceReply)

		if MsgIsNew(msg) {
			SetMsg(msg)

			fmt.Println("    ", msg.String())

			if ok1 && len(bounce.Stamps) < 5 {
				if isp2p {
					for i := 0; i < numReplies; i++ {
						bounceReply = new(messages.BounceReply)
						bounceReply.SetPeer2Peer(true)

						bounceReply.Number = cntreply
						cntreply++
						bounceReply.Name = name + "->" + strings.TrimSpace(bounce.Name)

						bounceReply.Timestamp = bounce.Timestamp
						bounceReply.Stamps = append(bounceReply.Stamps, bounce.Stamps...)

						for j := 0; j < numStamps; j++ {
							bounceReply.Stamps = append(bounceReply.Stamps, primitives.NewTimestampNow())
						}

						bounceReply.SetOrigin(bounce.GetOrigin())
						bounceReply.SetNetworkOrigin(bounce.GetNetworkOrigin())

						SetMsg(msg)
						p2pProxy.Send(bounceReply)

						p2pSent++
					}
					p2pRequestReceived++
				} else {
					bounce.Stamps = append(bounce.Stamps, primitives.NewTimestampNow())
					bounce.Number = cntreq
					bounce.Name = strings.TrimSpace(bounce.Name) + "-" + name
					cntreq++

					SetMsg(msg)
					p2pProxy.Send(msg)

					broadcastReceived++
					broadcastSent++
				}
			}
			if false && ok2 && len(bounceReply.Stamps) < 5 {
				bounceReply.Stamps = append(bounceReply.Stamps, primitives.NewTimestampNow())

				SetMsg(msg)
				p2pProxy.Send(msg)

				p2pReceived++
				p2pSent++
			}

		} else {
			oldcnt++
			fmt.Println("OLD:", msg.String())
		}

	}
}
Exemplo n.º 28
0
func newAuditServerFault() *AuditServerFault {
	msg := new(AuditServerFault)
	msg.Timestamp = primitives.NewTimestampNow()

	return msg
}
Exemplo n.º 29
0
func Test_Replay(test *testing.T) {

	type mh struct {
		hash [32]byte
		time interfaces.Timestamp
	}

	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()

	XTrans := 61440 //102400000 //61440 //145000

	var mhs []*mh

	start := primitives.NewTimestampNow()
	now := primitives.NewTimestampNow()

	for i := 0; i < XTrans; i++ {

		if (i+1)%1000 == 0 {

			buckets := len(r.Buckets)
			bcnt := 0
			for _, b := range r.Buckets {
				bcnt += len(b)
			}
			secs := now.GetTimeSeconds() - start.GetTimeSeconds()
			fmt.Printf("Test in %d minute, %d buckets, %d elements, %d center\n", Minutes(secs), buckets, bcnt, r.Center)
			// Now replay all the transactions we have collected.  NONE of them
			// should work.

			for in := 0; in < 1000; in++ {
				i := rand.Int() % len(mhs)
				x := mhs[i]
				if r.IsTSValid_(constants.INTERNAL_REPLAY, x.hash, x.time, now) {
					fmt.Printf("Failed Repeat Test %d\n", i)
					test.Fail()
					return
				}
			}
			time.Sleep(10 * time.Millisecond)
		}

		if (i+1)%10000 == 0 {
			mhs = mhs[:0]
		}

		// We are going to remember some large set of transactions.
		x := new(mh)
		x.hash = primitives.Sha([]byte(fmt.Sprintf("h%d", i))).Fixed()
		mhs = append(mhs, x)

		// Build a valid transaction somewhere +/- span hours of now
		delta := int64(float32(spanMin*2) * rand.Float32())
		ntime := now.GetTimeSeconds()/60 - spanMin + delta
		x.time = primitives.NewTimestampFromSeconds(uint32(ntime * 60))

		if _, ok := r.Valid(constants.INTERNAL_REPLAY, x.hash, x.time, now); !ok {
			mnow := Minutes(now.GetTimeSeconds())
			mx := Minutes(x.time.GetTimeSeconds())
			fmt.Printf("Failed an element in the time range. Test %d element Time: %d now %d Diff %d\n", i, mx, mnow, mx-mnow)
			test.Fail()
			return
		}

		// The first time we test, it should be valid.
		if !r.IsTSValid_(constants.INTERNAL_REPLAY, x.hash, x.time, now) {
			fmt.Println("Failed Test ", i, "first")
			test.Fail()
			return
		}

		// An immediate replay!  Should fail!
		if r.IsTSValid_(constants.INTERNAL_REPLAY, x.hash, x.time, now) {
			fmt.Println("Failed Test ", i, "second")
			test.Fail()
			return
		}

		x = new(mh)
		x.hash = primitives.Sha([]byte(fmt.Sprintf("xh%d", i))).Fixed()

		// Build a invalid transaction > span in the past
		delta = now.GetTimeSeconds()/60 - spanMin + 1 + rand.Int63()%20
		ntime = now.GetTimeSeconds()/60 - delta
		x.time = primitives.NewTimestampFromSeconds(uint32(ntime * 60))

		// should not be valid
		if _, ok := r.Valid(constants.INTERNAL_REPLAY, x.hash, x.time, now); ok {
			mnow := Minutes(now.GetTimeSeconds())
			mx := Minutes(x.time.GetTimeSeconds())
			fmt.Printf("Okayed an element out of time range. Test %d element Time: %d now %d Diff %d\n", i, mx, mnow, mx-mnow)
			test.Fail()
			return
		}

		// The first time we test, it should not be valid.
		if r.IsTSValid_(constants.INTERNAL_REPLAY, x.hash, x.time, now) {
			fmt.Println("Failed Test ", i, "bad first")
			test.Fail()
			return
		}

		// Move time forward somewhere between 0 to 15 minutes
		now = primitives.NewTimestampFromMilliseconds(uint64(now.GetTimeMilli() + rand.Int63()%(speed)))

	}

	fmt.Println("Simulation ran from", time.Unix(start.GetTimeSeconds(), 0), "to", time.Unix(now.GetTimeSeconds(), 0))

}
Exemplo n.º 30
0
func TestServerFaultMarshalUnmarshal(t *testing.T) {
	sf := new(ServerFault)

	sf.Timestamp = primitives.NewTimestampNow()
	sf.ServerID = testHelper.NewRepeatingHash(1)
	sf.AuditServerID = testHelper.NewRepeatingHash(2)

	sf.VMIndex = 0x33
	sf.DBHeight = 0x44556677
	sf.Height = 0x88990011

	core, err := sf.MarshalCore()
	if err != nil {
		t.Errorf("%v", err)
	}
	for i := 0; i < 10; i++ {
		priv := testHelper.NewPrimitivesPrivateKey(uint64(i))
		sig := priv.Sign(core)
		sf.SignatureList.List = append(sf.SignatureList.List, sig)
	}
	sf.SignatureList.Length = uint32(len(sf.SignatureList.List))

	bin, err := sf.MarshalBinary()
	if err != nil {
		t.Errorf("%v", err)
	}

	sf2 := new(ServerFault)
	rest, err := sf2.UnmarshalBinaryData(bin)
	if err != nil {
		t.Errorf("%v", err)
	}
	if len(rest) > 0 {
		t.Errorf("Unexpected extra piece of data - %x", rest)
	}
	t.Logf("%v", sf.String())
	t.Logf("%v", sf2.String())

	if sf.Timestamp.GetTimeMilliUInt64() !=
		sf2.Timestamp.GetTimeMilliUInt64() {
		t.Errorf("Invalid Timestamp")
	}
	if sf.ServerID.IsSameAs(sf2.ServerID) == false {
		t.Errorf("Invalid ServerID")
	}
	if sf.AuditServerID.IsSameAs(sf2.AuditServerID) == false {
		t.Errorf("Invalid AuditServerID")
	}
	if sf.VMIndex != sf2.VMIndex {
		t.Errorf("Invalid VMIndex")
	}
	if sf.DBHeight != sf2.DBHeight {
		t.Errorf("Invalid DBHeight")
	}
	if sf.Height != sf2.Height {
		t.Errorf("Invalid Height")
	}

	if sf.SignatureList.Length != sf2.SignatureList.Length {
		t.Errorf("Invalid SignatureList.Length")
	}
	if len(sf.SignatureList.List) != len(sf2.SignatureList.List) {
		t.Errorf("Invalid len of SignatureList.List")
	} else {
		for i := range sf.SignatureList.List {
			if sf.SignatureList.List[i].IsSameAs(sf2.SignatureList.List[i]) == false {
				t.Errorf("Invalid SignatureList.List at %v", i)
			}
		}
	}
}