Пример #1
0
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)
}
Пример #2
0
func TestOutECAddress(t *testing.T) {
	h, err := primitives.HexToHash("ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973")
	if err != nil {
		t.Error(err)
	}
	add := h.(interfaces.IAddress)
	outECAdd := NewOutECAddress(add, 12345678)
	str := outECAdd.String()

	t.Logf("outECAdd str - %v", str)

	if strings.Contains(str, "ecoutput") == false {
		t.Error("'ecoutput' not found")
	}
	if strings.Contains(str, "0.12345678") == false {
		t.Error("'0.12345678' not found")
	}
	if strings.Contains(str, "EC3ZMxDt8xUBKBmrmzLwSpnMHkdptLS8gTSf8NQhVf7vpAWqNE2p") == false {
		t.Error("'EC3ZMxDt8xUBKBmrmzLwSpnMHkdptLS8gTSf8NQhVf7vpAWqNE2p' not found")
	}
	if strings.Contains(str, "0000000000bc614e") == false {
		t.Error("'0000000000bc614e' not found")
	}
	if strings.Contains(str, "ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973") == false {
		t.Error("'ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973' not found")
	}
}
Пример #3
0
func getECblock(hash string) *ECBlockHolder {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}

	dbase := StatePointer.GetAndLockDB()
	ecblk, err := dbase.FetchECBlock(mr)
	StatePointer.UnlockDB()

	if ecblk == nil || err != nil {
		return nil
	}
	if ecblk.GetHeader() == nil {
		return nil
	}

	holder := new(ECBlockHolder)
	holder.ECBlock = ecblk
	length := 0
	zero := primitives.NewZeroHash()
	for _, e := range ecblk.GetEntryHashes() {
		if e != nil && !e.IsSameAs(zero) {
			length++
		}
	}
	holder.Length = length

	return holder
}
Пример #4
0
func TestTransAddressMarshalUnmarshal(t *testing.T) {
	ta := new(TransAddress)
	ta.SetAmount(12345678)
	h, err := primitives.HexToHash("ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973")
	if err != nil {
		t.Error(err)
	}
	add := h.(interfaces.IAddress)
	ta.SetAddress(add)

	hex, err := ta.MarshalBinary()
	if err != nil {
		t.Error(err)
	}
	ta2 := new(TransAddress)
	err = ta2.UnmarshalBinary(hex)
	if err != nil {
		t.Error(err)
	}
	json1, err := ta.JSONString()
	if err != nil {
		t.Error(err)
	}
	json2, err := ta2.JSONString()
	if err != nil {
		t.Error(err)
	}
	if json1 != json2 {
		t.Error("JSONs are not identical")
	}
}
Пример #5
0
func getFactTransaction(hash string) interfaces.ITransaction {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}

	dbase := StatePointer.GetAndLockDB()
	trans, err := dbase.FetchFactoidTransaction(mr)
	StatePointer.UnlockDB()

	if trans == nil || err != nil {
		return nil
	}
	if trans.GetInputs() == nil {
		return nil
	}
	status := getFactoidAck(hash)
	if status == nil {
		return struct {
			interfaces.ITransaction
			wsapi.FactoidTxStatus
		}{trans, *status}
	}
	return struct {
		interfaces.ITransaction
		wsapi.FactoidTxStatus
	}{trans, *status}
}
Пример #6
0
func getFblock(hash string) *FBlockHolder {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}

	dbase := StatePointer.GetAndLockDB()
	fblk, err := dbase.FetchFBlock(mr)
	StatePointer.UnlockDB()

	if fblk == nil || err != nil {
		return nil
	}
	bytes, err := fblk.MarshalBinary()
	if err != nil {
		return nil
	}
	holder := new(FBlockHolder)
	err = holder.UnmarshalBinary(bytes)
	if err != nil {
		return nil
	}

	holder.Length = len(holder.Transactions)
	return holder
}
Пример #7
0
func TestInAddress(t *testing.T) {
	h, err := primitives.HexToHash("ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973")
	if err != nil {
		t.Error(err)
	}
	add := h.(interfaces.IAddress)
	inAdd := NewInAddress(add, 12345678)
	str := inAdd.String()

	t.Logf("InAdd str - %v", str)

	if strings.Contains(str, "input") == false {
		t.Error("'input' not found")
	}
	if strings.Contains(str, "0.12345678") == false {
		t.Error("'0.12345678' not found")
	}
	if strings.Contains(str, "FA3mHjgsVvQJjVbvJpy67deDKzEsqc8FsLU122i8Tj76rmakpqRL") == false {
		t.Error("'FA3mHjgsVvQJjVbvJpy67deDKzEsqc8FsLU122i8Tj76rmakpqRL' not found")
	}
	if strings.Contains(str, "0000000000bc614e") == false {
		t.Error("'0000000000bc614e' not found")
	}
	if strings.Contains(str, "ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973") == false {
		t.Error("'ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973' not found")
	}
}
Пример #8
0
func getEblock(hash string) *EblockHolder {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}
	holder := new(EblockHolder)

	dbase := StatePointer.GetAndLockDB()
	eblk, err := dbase.FetchEBlock(mr)
	StatePointer.UnlockDB()

	if eblk == nil || err != nil {
		return nil
	}
	bytes, err := eblk.JSONByte()
	if err != nil {
		return nil
	}
	err = json.Unmarshal(bytes, holder)
	if err != nil {
		return nil
	}

	if keymr, err := eblk.KeyMR(); err != nil {
		holder.KeyMR = "Error"
	} else {
		holder.KeyMR = keymr.String()
	}
	holder.BodyMR = eblk.BodyKeyMR().String()
	holder.FullHash = eblk.GetHash().String()

	entries := eblk.GetEntryHashes()
	count := 0
	for _, entry := range entries {
		if len(entry.String()) < 32 {
			continue
		} else if entry.String()[:10] == "0000000000" {
			ent := new(EntryHolder)
			ent.Hash = "Minute Marker"
			num := entry.String()[63:]
			if num == "a" {
				num = "10"
			}
			ent.ChainID = num

			holder.Entries = append(holder.Entries, *ent)
			continue
		}
		ent := getEntry(entry.String())
		count++
		if ent != nil {
			ent.Hash = entry.String()
			holder.Entries = append(holder.Entries, *ent)
		}
	}
	holder.Header.EntryCount = count

	return holder
}
Пример #9
0
func TestHandleEntryBlock(t *testing.T) {
	context := testHelper.CreateWebContext()
	chain, err := primitives.HexToHash("df3ade9eec4b08d5379cc64270c30ea7315d8a8a1a69efe2b98a60ecdd69e604")
	if err != nil {
		t.Error(err)
	}

	dbo := context.Server.Env["state"].(interfaces.IState).GetAndLockDB()
	defer context.Server.Env["state"].(interfaces.IState).UnlockDB()

	blocks, err := dbo.FetchAllEBlocksByChain(chain)
	if err != nil {
		t.Error(err)
	}
	fetched := 0
	for _, b := range blocks {
		hash := b.(*entryBlock.EBlock).DatabasePrimaryIndex().String()
		hash2 := b.(*entryBlock.EBlock).DatabaseSecondaryIndex().String()

		testHelper.ClearContextResponseWriter(context)
		HandleEntryBlock(context, hash)

		eBlock := new(EBlock)

		testHelper.UnmarshalRespDirectly(context, eBlock)

		if eBlock.Header.ChainID != "df3ade9eec4b08d5379cc64270c30ea7315d8a8a1a69efe2b98a60ecdd69e604" {
			t.Errorf("Wrong ChainID - %v", eBlock.Header.ChainID)
			t.Errorf("eBlock - %v", eBlock)
			t.Errorf("%v", testHelper.GetBody(context))
		}

		if eBlock.Header.DBHeight != int64(b.(*entryBlock.EBlock).GetHeader().GetDBHeight()) {
			t.Errorf("DBHeight is wrong - %v vs %v", eBlock.Header.DBHeight, b.(*entryBlock.EBlock).GetHeader().GetDBHeight())
		}

		testHelper.ClearContextResponseWriter(context)
		HandleEntryBlock(context, hash2)

		eBlock = new(EBlock)

		testHelper.UnmarshalRespDirectly(context, eBlock)

		if eBlock.Header.ChainID != "df3ade9eec4b08d5379cc64270c30ea7315d8a8a1a69efe2b98a60ecdd69e604" {
			t.Errorf("Wrong ChainID - %v", eBlock.Header.ChainID)
			t.Errorf("%v", testHelper.GetBody(context))
		}

		if eBlock.Header.DBHeight != int64(b.(*entryBlock.EBlock).GetHeader().GetDBHeight()) {
			t.Errorf("DBHeight is wrong - %v vs %v", eBlock.Header.DBHeight, b.(*entryBlock.EBlock).GetHeader().GetDBHeight())
		}

		fetched++
	}
	if fetched != testHelper.BlockCount {
		t.Errorf("Fetched %v blocks, expected %v", fetched, testHelper.BlockCount)
	}
}
Пример #10
0
func getAllChainEntries(chainIDString string) []SearchedStruct {
	arr := make([]SearchedStruct, 0)
	chainID, err := primitives.HexToHash(chainIDString)
	if err != nil {
		return nil
	}
	s := new(SearchedStruct)
	s.Type = "chainhead"
	s.Input = chainID.String()

	dbase := StatePointer.GetAndLockDB()
	mr, err := dbase.FetchHeadIndexByChainID(chainID)
	StatePointer.UnlockDB()

	if err != nil || mr == nil {
		return nil
	}
	s.Content = mr.String()
	arr = append(arr[:], *s)
	if err != nil {
		return nil
	}

	entries := make([]interfaces.IEBEntry, 0)

	dbase = StatePointer.GetAndLockDB()
	eblks, err := dbase.FetchAllEBlocksByChain(chainID)
	if err != nil {
		StatePointer.UnlockDB()
		return nil
	}

	for _, eblk := range eblks {
		hashes := eblk.GetEntryHashes()
		for _, hash := range hashes {
			entry, err := dbase.FetchEntry(hash)
			if err != nil || entry == nil {
				continue
			}
			entries = append(entries, entry)
		}
	}
	//entries, err := dbase.FetchAllEntriesByChainID(chainID)
	StatePointer.UnlockDB()
	if err != nil {
		return nil
	}

	for _, entry := range entries {
		s := new(SearchedStruct)
		s.Type = "entry"
		e := getEntry(entry.GetHash().String())
		s.Content = e
		s.Input = entry.GetHash().String()
		arr = append(arr[:], *s)
	}
	return arr
}
Пример #11
0
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
}
Пример #12
0
func TestDBSEMisc(t *testing.T) {
	dbe := new(DBEntry)
	hash, err := primitives.HexToHash("000000000000000000000000000000000000000000000000000000000000000a")
	if err != nil {
		t.Error(err)
	}
	dbe.ChainID = hash
	hash, err = primitives.HexToHash("000000000000000000000000000000000000000000000000000000000000000b")
	if err != nil {
		t.Error(err)
	}
	dbe.KeyMR = hash

	hash = dbe.GetChainID()
	if hash.String() != "000000000000000000000000000000000000000000000000000000000000000a" {
		t.Fail()
	}
	hash = dbe.GetKeyMR()
	if hash.String() != "000000000000000000000000000000000000000000000000000000000000000b" {
		t.Fail()
	}
	/*
		dbe2, err := NewDBEntry(dbe)
		if err != nil {
			t.Error(err)
		}
		if dbe2 == nil {
			t.Fail()
		}

		hash = dbe2.GetChainID()
		if hash.String() != "000000000000000000000000000000000000000000000000000000000000000a" {
			t.Fail()
		}
		hash, err = dbe2.GetKeyMR()
		if err != nil {
			t.Error(err)
		}
		if hash.String() != "000000000000000000000000000000000000000000000000000000000000000b" {
			t.Fail()
		}
	*/
}
Пример #13
0
func HandleDirectoryBlock(ctx *web.Context, hashkey string) {
	state := ctx.Server.Env["state"].(interfaces.IState)

	d := new(DBlock)

	h, err := primitives.HexToHash(hashkey)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}

	dbase := state.GetDB()

	block, err := dbase.FetchDBlockByKeyMR(h)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}
	if block == nil {
		block, err = dbase.FetchDBlockByHash(h)
		if err != nil {
			wsLog.Error(err)
			ctx.WriteHeader(httpBad)
			ctx.Write([]byte(err.Error()))
			return
		}
		if block == nil {
			//TODO: Handle block not found
			return
		}
	}

	d.Header.PrevBlockKeyMR = block.GetHeader().GetPrevKeyMR().String()
	d.Header.SequenceNumber = block.GetHeader().GetDBHeight()
	d.Header.Timestamp = block.GetHeader().GetTimestamp() * 60
	for _, v := range block.GetDBEntries() {
		l := new(EBlockAddr)
		l.ChainID = v.GetChainID().String()
		l.KeyMR = v.GetKeyMR().String()
		d.EntryBlockList = append(d.EntryBlockList, *l)
	}

	if p, err := json.Marshal(d); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		ctx.Write(p)
	}
}
Пример #14
0
func getDblock(hash string) *DblockHolder {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}
	holder := new(DblockHolder)

	dbase := StatePointer.GetAndLockDB()
	dblk, err := dbase.FetchDBlock(mr)
	StatePointer.UnlockDB()

	if dblk == nil || err != nil {
		return nil
	}
	bytes, err := dblk.JSONByte()
	if err != nil {
		return nil
	}
	err = json.Unmarshal(bytes, holder)
	if err != nil {
		return nil
	}

	blocks := dblk.GetDBEntries()
	for _, block := range blocks {
		if len(block.GetKeyMR().String()) < 32 {
			continue
		} else if block.GetChainID().String()[:10] == "0000000000" {
			// Admin/FC/EC block
			switch block.GetChainID().String() {
			case "000000000000000000000000000000000000000000000000000000000000000a":
				holder.AdminBlock.ChainID = block.GetChainID().String()
				holder.AdminBlock.KeyMr = block.GetKeyMR().String()
			case "000000000000000000000000000000000000000000000000000000000000000c":
				holder.EntryCreditBlock.ChainID = block.GetChainID().String()
				holder.EntryCreditBlock.KeyMr = block.GetKeyMR().String()
			case "000000000000000000000000000000000000000000000000000000000000000f":
				holder.FactoidBlock.ChainID = block.GetChainID().String()
				holder.FactoidBlock.KeyMr = block.GetKeyMR().String()
			}
			continue
		}
		blk := getEblock(block.GetKeyMR().String())
		if blk != nil {
			holder.EBlocks = append(holder.EBlocks, *blk)
		}
	}

	holder.FullHash = dblk.GetHash().String()
	holder.KeyMR = dblk.GetKeyMR().String()

	ts := dblk.GetTimestamp()
	holder.Header.FormatedTimeStamp = ts.String()
	return holder
}
Пример #15
0
func HandleGetRaw(ctx *web.Context, hashkey string) {
	state := ctx.Server.Env["state"].(interfaces.IState)

	//TODO: var block interfaces.BinaryMarshallable
	d := new(RawData)

	h, err := primitives.HexToHash(hashkey)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}

	dbase := state.GetDB()

	var b []byte

	// try to find the block data in db and return the first one found
	if block, _ := dbase.FetchFBlockByKeyMR(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchDBlockByKeyMR(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchABlockByKeyMR(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchEBlockByKeyMR(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchECBlockByKeyMR(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchEntryByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchFBlockByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchDBlockByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchABlockByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchEBlockByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ := dbase.FetchECBlockByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	}

	d.Data = hex.EncodeToString(b)

	if p, err := json.Marshal(d); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		ctx.Write(p)
	}
}
Пример #16
0
func TestAddressMisc(t *testing.T) {
	h, err := primitives.HexToHash("ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973")
	if err != nil {
		t.Error(err)
	}
	add := CreateAddress(h)
	str := add.String()
	if strings.Contains(str, "ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973") == false {
		t.Errorf("String doesn't contain an expected address:\n%v", str)
	}
}
Пример #17
0
func TestDBSEMarshalUnmarshal(t *testing.T) {
	dbe := new(DBEntry)

	hash, err := primitives.HexToHash("000000000000000000000000000000000000000000000000000000000000000a")
	if err != nil {
		t.Error(err)
	}
	dbe.ChainID = hash
	hash, err = primitives.HexToHash("000000000000000000000000000000000000000000000000000000000000000b")
	if err != nil {
		t.Error(err)
	}
	dbe.KeyMR = hash

	hex, err := dbe.MarshalBinary()
	if err != nil {
		t.Error(err)
	}

	dbe2 := new(DBEntry)
	err = dbe2.UnmarshalBinary(hex)
	if err != nil {
		t.Error(err)
	}

	hex2, err := dbe2.MarshalBinary()
	if err != nil {
		t.Error(err)
	}

	if len(hex) != len(hex2) {
		t.Fail()
	}

	for i := range hex {
		if hex[i] != hex2[i] {
			t.Fail()
		}
	}
}
Пример #18
0
func HandleV2RawData(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	hashkey := new(HashRequest)
	err := MapToObject(params, hashkey)
	if err != nil {
		panic(reflect.TypeOf(params))
		return nil, NewInvalidParamsError()
	}

	h, err := primitives.HexToHash(hashkey.Hash)
	if err != nil {
		return nil, NewInvalidHashError()
	}

	var block interfaces.BinaryMarshallable
	var b []byte

	if block, _ = state.FetchECTransactionByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ = state.FetchFactoidTransactionByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	} else if block, _ = state.FetchEntryByHash(h); block != nil {
		b, _ = block.MarshalBinary()
	}

	if b == nil {
		dbase := state.GetAndLockDB()
		defer state.UnlockDB()

		// try to find the block data in db and return the first one found
		if block, _ = dbase.FetchFBlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchDBlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchABlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchEBlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchECBlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchFBlock(h); block != nil {
			b, _ = block.MarshalBinary()
		} else if block, _ = dbase.FetchEntry(h); block != nil {
			b, _ = block.MarshalBinary()
		} else {
			return nil, NewEntryNotFoundError()
		}
	}

	d := new(RawDataResponse)
	d.Data = hex.EncodeToString(b)
	return d, nil
}
Пример #19
0
func getEcTransaction(hash string) interfaces.IECBlockEntry {
	mr, err := primitives.HexToHash(hash)
	if err != nil {
		return nil
	}

	dbase := StatePointer.GetAndLockDB()
	trans, err := dbase.FetchECTransaction(mr)
	StatePointer.UnlockDB()

	if trans == nil || err != nil {
		return nil
	}
	if trans.GetEntryHash() == nil {
		return nil
	}
	return trans
}
Пример #20
0
func HandleEntry(ctx *web.Context, hashkey string) {
	state := ctx.Server.Env["state"].(interfaces.IState)

	e := new(EntryStruct)

	h, err := primitives.HexToHash(hashkey)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}

	dbase := state.GetDB()

	entry, err := dbase.FetchEntryByHash(h)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}
	if entry == nil {
		//TODO: Handle block not found
		return
	}

	e.ChainID = entry.GetChainIDHash().String()
	e.Content = hex.EncodeToString(entry.GetContent())
	for _, v := range entry.ExternalIDs() {
		e.ExtIDs = append(e.ExtIDs, hex.EncodeToString(v))
	}

	if p, err := json.Marshal(e); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		ctx.Write(p)
	}

}
Пример #21
0
func HandleV2DirectoryBlock(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	keymr := new(KeyMRRequest)
	err := MapToObject(params, keymr)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	h, err := primitives.HexToHash(keymr.KeyMR)
	if err != nil {
		return nil, NewInvalidHashError()
	}

	dbase := state.GetAndLockDB()
	defer state.UnlockDB()

	block, err := dbase.FetchDBlock(h)
	if err != nil {
		return nil, NewInvalidHashError()
	}
	if block == nil {
		block, err = dbase.FetchDBlock(h)
		if err != nil {
			return nil, NewInvalidHashError()
		}
		if block == nil {
			return nil, NewBlockNotFoundError()
		}
	}

	d := new(DirectoryBlockResponse)
	d.Header.PrevBlockKeyMR = block.GetHeader().GetPrevKeyMR().String()
	d.Header.SequenceNumber = int64(block.GetHeader().GetDBHeight())
	d.Header.Timestamp = block.GetHeader().GetTimestamp().GetTimeSeconds()
	for _, v := range block.GetDBEntries() {
		l := new(EBlockAddr)
		l.ChainID = v.GetChainID().String()
		l.KeyMR = v.GetKeyMR().String()
		d.EntryBlockList = append(d.EntryBlockList, *l)
	}

	return d, nil
}
Пример #22
0
func (a *Anchor) readConfig() {
	anchorLog.Info("readConfig")
	a.cfg = util.ReadConfig("")
	a.confirmationsNeeded = a.cfg.Anchor.ConfirmationsNeeded
	a.fee, _ = btcutil.NewAmount(a.cfg.Btc.BtcTransFee)

	var err error
	a.serverPrivKey, err = primitives.NewPrivateKeyFromHex(a.cfg.App.LocalServerPrivKey)
	if err != nil {
		panic("Cannot parse Server Private Key from configuration file: " + err.Error())
	}
	a.serverECKey, err = primitives.NewPrivateKeyFromHex(a.cfg.Anchor.ServerECPrivKey)
	if err != nil {
		panic("Cannot parse Server EC Key from configuration file: " + err.Error())
	}
	a.anchorChainID, err = primitives.HexToHash(a.cfg.Anchor.AnchorChainID)
	anchorLog.Debug("anchorChainID: ", a.anchorChainID)
	if err != nil || a.anchorChainID == nil {
		panic("Cannot parse Server AnchorChainID from configuration file: " + err.Error())
	}
}
Пример #23
0
func HandleChainHead(ctx *web.Context, hashkey string) {
	state := ctx.Server.Env["state"].(interfaces.IState)

	c := new(CHead)

	h, err := primitives.HexToHash(hashkey)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}

	dbase := state.GetDB()

	mr, err := dbase.FetchHeadIndexByChainID(h)
	if err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}
	if mr == nil {
		err := fmt.Errorf("Missing Chain Head")
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	}
	c.ChainHead = mr.String()
	if p, err := json.Marshal(c); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		ctx.Write(p)
	}

}
Пример #24
0
func HandleV2ChainHead(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	chainid := new(ChainIDRequest)
	err := MapToObject(params, chainid)
	if err != nil {
		return nil, NewInvalidParamsError()
	}
	h, err := primitives.HexToHash(chainid.ChainID)
	if err != nil {
		return nil, NewInvalidHashError()
	}

	dbase := state.GetAndLockDB()
	defer state.UnlockDB()

	c := new(ChainHeadResponse)

	// get the pending chain head from the current or previous process list in
	// the state
	lh := state.GetLeaderHeight()
	pend1 := state.GetNewEBlocks(lh, h)
	pend2 := state.GetNewEBlocks(lh-1, h)
	if pend1 != nil || pend2 != nil {
		c.ChainInProcessList = true
	}

	// get the chain head from the database
	mr, err := dbase.FetchHeadIndexByChainID(h)
	if err != nil {
		return nil, NewInvalidHashError()
	}
	if mr == nil {
		if c.ChainInProcessList == false {
			return nil, NewMissingChainHeadError()
		}
	} else {
		c.ChainHead = mr.String()
	}

	return c, nil
}
Пример #25
0
func TestTransAddressMisc(t *testing.T) {
	ta := new(TransAddress)
	ta.SetAmount(12345678)
	h, err := primitives.HexToHash("ec9f1cefa00406b80d46135a53504f1f4182d4c0f3fed6cca9281bc020eff973")
	if err != nil {
		t.Error(err)
	}
	add := h.(interfaces.IAddress)
	ta.SetAddress(add)

	text, err := ta.CustomMarshalText()
	if err != nil {
		t.Error(err)
	}
	if text != nil {
		t.Error("Text isn't nil when it should be")
	}
	str := ta.String()
	if str != "" {
		t.Error("Str isn't empty when it should be")
	}
}
Пример #26
0
func HandleV2Entry(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	hashkey := new(HashRequest)
	err := MapToObject(params, hashkey)
	if err != nil {
		return nil, NewInvalidParamsError()
	}
	e := new(EntryResponse)

	h, err := primitives.HexToHash(hashkey.Hash)
	if err != nil {
		return nil, NewInvalidHashError()
	}

	entry, err := state.FetchEntryByHash(h)
	if err != nil {
		return nil, NewInternalError()
	}
	if entry == nil {
		dbase := state.GetAndLockDB()
		defer state.UnlockDB()

		entry, err = dbase.FetchEntry(h)
		if err != nil {
			return nil, NewInvalidHashError()
		}
		if entry == nil {
			return nil, NewEntryNotFoundError()
		}
	}

	e.ChainID = entry.GetChainIDHash().String()
	e.Content = hex.EncodeToString(entry.GetContent())
	for _, v := range entry.ExternalIDs() {
		e.ExtIDs = append(e.ExtIDs, hex.EncodeToString(v))
	}

	return e, nil
}
Пример #27
0
func HandleV2Receipt(state interfaces.IState, params interface{}) (interface{}, *primitives.JSONError) {
	hashkey := new(HashRequest)
	err := MapToObject(params, hashkey)
	if err != nil {
		return nil, NewInvalidParamsError()
	}

	h, err := primitives.HexToHash(hashkey.Hash)
	if err != nil {
		return nil, NewInvalidHashError()
	}

	dbase := state.GetAndLockDB()
	defer state.UnlockDB()

	receipt, err := receipts.CreateFullReceipt(dbase, h)
	if err != nil {
		return nil, NewReceiptError()
	}
	resp := new(ReceiptResponse)
	resp.Receipt = receipt

	return resp, nil
}
Пример #28
0
func HandleEntryCreditBalance(ctx *web.Context, eckey string) {
	state := ctx.Server.Env["state"].(interfaces.IState)

	var b FactoidBalance
	adr, err := primitives.HexToHash(eckey)
	if err == nil {
		b = FactoidBalance{Response: "Invalid Address", Success: false}
	}
	if err == nil {
		v := int64(state.GetFactoidState().GetECBalance(adr.Fixed()))
		str := fmt.Sprintf("%d", v)
		b = FactoidBalance{Response: str, Success: true}
	} else {
		b = FactoidBalance{Response: err.Error(), Success: false}
	}

	if p, err := json.Marshal(b); err != nil {
		wsLog.Error(err)
		return
	} else {
		ctx.Write(p)
	}

}
Пример #29
0
func TestBootStrappingIdentity(t *testing.T) {
	state := testHelper.CreateEmptyTestState()

	state.NetworkNumber = constants.NETWORK_MAIN
	if !state.GetNetworkBootStrapIdentity().IsSameAs(primitives.NewZeroHash()) {
		t.Errorf("Bootstrap Identity Mismatch on MAIN")
	}
	key, _ := primitives.HexToHash("0426a802617848d4d16d87830fc521f4d136bb2d0c352850919c2679f189613a")
	if !state.GetNetworkBootStrapKey().IsSameAs(key) {
		t.Errorf("Bootstrap Identity Key Mismatch on MAIN")
	}

	state.NetworkNumber = constants.NETWORK_TEST
	if !state.GetNetworkBootStrapIdentity().IsSameAs(primitives.NewZeroHash()) {
		t.Errorf("Bootstrap Identity Mismatch on TEST")
	}

	key, _ = primitives.HexToHash("49b6edd274e7d07c94d4831eca2f073c207248bde1bf989d2183a8cebca227b7")
	if !state.GetNetworkBootStrapKey().IsSameAs(key) {
		t.Errorf("Bootstrap Identity Key Mismatch on TEST")
	}

	state.NetworkNumber = constants.NETWORK_LOCAL
	id, _ := primitives.HexToHash("38bab1455b7bd7e5efd15c53c777c79d0c988e9210f1da49a99d95b3a6417be9")
	if !state.GetNetworkBootStrapIdentity().IsSameAs(id) {
		t.Errorf("Bootstrap Identity Mismatch on LOCAL")
	}
	key, _ = primitives.HexToHash("cc1985cdfae4e32b5a454dfda8ce5e1361558482684f3367649c3ad852c8e31a")
	if !state.GetNetworkBootStrapKey().IsSameAs(key) {
		t.Errorf("Bootstrap Identity Key Mismatch on LOCAL")
	}

	state.NetworkNumber = constants.NETWORK_CUSTOM
	id, _ = primitives.HexToHash("38bab1455b7bd7e5efd15c53c777c79d0c988e9210f1da49a99d95b3a6417be9")
	if !state.GetNetworkBootStrapIdentity().IsSameAs(id) {
		t.Errorf("Bootstrap Identity Mismatch on CUSTOM")
	}
	key, _ = primitives.HexToHash("cc1985cdfae4e32b5a454dfda8ce5e1361558482684f3367649c3ad852c8e31a")
	if !state.GetNetworkBootStrapKey().IsSameAs(key) {
		t.Errorf("Bootstrap Identity Key Mismatch on CUSTOM")
	}

}
Пример #30
0
// Go through the factoid exchange rate chain and determine if an FER change should be scheduled
func (this *State) ProcessRecentFERChainEntries() {
	// Find the FER entry chain
	FERChainHash, err := primitives.HexToHash(this.FERChainId)
	if err != nil {
		this.Println("The FERChainId couldn't be turned into a IHASH")
		return
	}

	//  Get the first eblock from the FERChain
	entryBlock, err := this.DB.FetchEBlockHead(FERChainHash)
	if err != nil {
		this.Println("Couldn't find the FER chain for id ", this.FERChainId)
		return
	}
	if entryBlock == nil {
		this.Println("FER Chain head found to be nil")
		return
	}

	this.Println("Checking last e block of FER chain with height of: ", entryBlock.GetHeader().GetDBHeight())
	this.Println("Current block height: ", this.GetDBHeightComplete())
	this.Println("BEFORE processing recent block: ")
	this.Println("    FERChangePrice: ", this.FERChangePrice)
	this.Println("    FERChangeHeight: ", this.FERChangeHeight)
	this.Println("    FERPriority: ", this.FERPriority)
	this.Println("    FERPrioritySetHeight: ", this.FERPrioritySetHeight)
	this.Println("    FER current: ", this.GetFactoshisPerEC())

	// Check to see if a price change targets the next block
	if this.FERChangeHeight == (this.GetDBHeightComplete())+1 {
		this.FactoshisPerEC = this.FERChangePrice
		this.FERChangePrice = 0
		this.FERChangeHeight = 1
	}

	// Check for the need to clear the priority
	// (this.GetDBHeightComplete() >= 12) is import because height is a uint and can't break logic if subtracted into false sub-zero
	if (this.GetDBHeightComplete() >= 12) &&
		(this.GetDBHeightComplete()-12) >= this.FERPrioritySetHeight {
		this.FERPrioritySetHeight = 0
		this.FERPriority = 0
		// Now the next entry to come through with a priority of 1 or more will be considered
	}

	// Check last entry block method
	if entryBlock.GetHeader().GetDBHeight() == this.GetDBHeightComplete()-1 {

		entryHashes := entryBlock.GetEntryHashes()

		// this.Println("Found FER entry hashes in a block as: ", entryHashes)
		// create a map of possible minute markers that may be found in the EBlock Body
		mins := make(map[string]uint8)
		for i := byte(0); i <= 10; i++ {
			h := make([]byte, 32)
			h[len(h)-1] = i
			mins[hex.EncodeToString(h)] = i
		}

		// Loop through the hashes from the last blocks FER entries and evaluate them individually
		for _, entryHash := range entryHashes {
			// if this entryhash is a minute mark then continue
			if _, exist := mins[entryHash.String()]; exist {
				continue
			}

			// Make sure the entry exists
			anEntry, err := this.DB.FetchEntry(entryHash)
			if err != nil {
				this.Println("Error during FetchEntryByHash: ", err)
				continue
			}
			if anEntry == nil {
				this.Println("Nil entry during FetchEntryByHash: ", entryHash)
				continue
			}

			if !this.ExchangeRateAuthorityIsValid(anEntry) {
				this.Println("Skipping non-authority FER chain entry", entryHash)
				continue
			}

			entryContent := anEntry.GetContent()
			// this.Println("Found content of an FER entry is:  ", string(entryContent))
			ferEntry := new(specialEntries.FEREntry)
			err = ferEntry.UnmarshalBinary(entryContent)
			if err != nil {
				this.Println("A FEREntry messgae didn't unmarshal correctly: ", err)
				continue
			}

			// Set it's resident height for validity checking
			ferEntry.SetResidentHeight(this.GetDBHeightComplete())

			if (this.FerEntryIsValid(ferEntry)) && (ferEntry.Priority > this.FERPriority) {
				this.Println(" Processing FER entry : ", string(entryContent))
				this.FERPriority = ferEntry.GetPriority()
				this.FERPrioritySetHeight = this.GetDBHeightComplete()
				this.FERChangePrice = ferEntry.GetTargetPrice()
				this.FERChangeHeight = ferEntry.GetTargetActivationHeight()

				// Adjust the target if needed
				if this.FERChangeHeight < (this.GetDBHeightComplete() + 2) {
					this.FERChangeHeight = this.GetDBHeightComplete() + 2
				}
			} else {
				this.Println(" Failed FER entry : ", string(entryContent))
			}
		}
	}

	this.Println("AFTER processing recent block: ")
	this.Println("    FERChangePrice: ", this.FERChangePrice)
	this.Println("    FERChangeHeight: ", this.FERChangeHeight)
	this.Println("    FERPriority: ", this.FERPriority)
	this.Println("    FERPrioritySetHeight: ", this.FERPrioritySetHeight)
	this.Println("    FER current: ", this.GetFactoshisPerEC())
	this.Println("----------------------------------")

	return
}