Beispiel #1
0
func CreateID(d *schema.ResourceData, meta interface{}) error {

	byteLength := d.Get("byte_length").(int)
	bytes := make([]byte, byteLength)

	n, err := rand.Reader.Read(bytes)
	if n != byteLength {
		return fmt.Errorf("generated insufficient random bytes")
	}
	if err != nil {
		return fmt.Errorf("error generating random bytes: %s", err)
	}

	b64Str := base64.RawURLEncoding.EncodeToString(bytes)
	hexStr := hex.EncodeToString(bytes)

	int := big.Int{}
	int.SetBytes(bytes)
	decStr := int.String()

	d.SetId(b64Str)
	d.Set("b64", b64Str)
	d.Set("hex", hexStr)
	d.Set("dec", decStr)

	return nil
}
Beispiel #2
0
/*
	The Join function
	The first fuction to be executed
	Alaows it gives the hash and id and request the finger table for the boost node
*/
func Join(test bool) { //

	//generate id
	me.nodeId = Index(generateNodeId(), BITS)
	nodeIdInt := me.nodeId
	me.storage = map[string]string{}

	//prepare finger table
	if test { //firstnode in the ring
		me.offset = 0
		for i, _ := range me.FingerTable {
			//compute the ith node
			two := big.NewInt(2)
			dist := big.Int{}
			dist.Exp(two, big.NewInt(int64(i)), nil)
			var ithNode big.Int
			ithNode.Add(&dist, &nodeIdInt)
			x := ringSize(BITS)
			ithNode.Mod(&ithNode, &x)
			//fill the fingr table row
			me.FingerTable[i][0] = ithNode.String()
			me.FingerTable[i][1] = me.nodeId.String()
			me.FingerTable[i][2] = me.address //this node address
		}
	} else { //not first node in the ring
		//initialize offset
		GetOffsetClient(me.target)
		updateFingerTable(nodeIdInt, me.target) //target server required
		go infornMySuccessor()
		go AutoUpdate() // initialize auto update
	}

}
Beispiel #3
0
func StartUP() {
	nodeStore := peerNode.NewNodeStore("", "")
	go read(nodeStore.OutFindNode, nodeStore.InNodes)
	running := true
	reader := bufio.NewReader(os.Stdin)

	for running {
		data, _, _ := reader.ReadLine()
		command := string(data)
		switch command {
		case "find":
			findNode, _ := new(big.Int).SetString("27", 10)
			// peerNode.Print(findNode)
			node := nodeStore.Get(findNode.String())
			// peerNode.Print(node.NodeId)
			fmt.Println(node)
		case "quit":
			running = false
		case "see":
			nodes := nodeStore.GetAllNodes()
			fmt.Println(nodes)
		case "self":
			fmt.Println("自己节点的id:")
			rootId := nodeStore.GetRootId()
			// peerNode.Print(rootId)
			fmt.Println(rootId)
		case "cap":
		case "odp":
		case "cdp":
		case "dump":
		}
	}
}
Beispiel #4
0
func (i BigInt) floatString(verb byte, prec int) string {
	switch verb {
	case 'f', 'F':
		str := fmt.Sprintf("%d", i.Int)
		if prec > 0 {
			str += "." + zeros(prec)
		}
		return str
	case 'e', 'E':
		// The exponent will alway be >= 0.
		sign := ""
		var x big.Int
		x.Set(i.Int)
		if x.Sign() < 0 {
			sign = "-"
			x.Neg(&x)
		}
		return eFormat(verb, prec, sign, x.String(), eExponent(&x))
	case 'g', 'G':
		// Exponent is always positive so it's easy.
		var x big.Int
		x.Set(i.Int)
		if eExponent(&x) >= prec {
			// Use e format.
			verb -= 2 // g becomes e.
			return trimEZeros(verb, i.floatString(verb, prec-1))
		}
		// Use f format, but this is just an integer.
		return fmt.Sprintf("%d", i.Int)
	default:
		Errorf("can't handle verb %c for big int", verb)
	}
	return ""
}
Beispiel #5
0
// Handles the load balancing event of a topio.
func (o *Overlay) handleBalance(msg *proto.Message, topicId *big.Int, prevHop *big.Int) (bool, error) {
	sid := topicId.String()

	// Fetch the topic or report not found
	o.lock.RLock()
	top, ok := o.topics[sid]
	topName := o.names[sid]
	o.lock.RUnlock()
	if !ok {
		// No error, but not handled either
		return false, nil
	}
	// Fetch the recipient and either forward or deliver
	node, err := top.Balance(prevHop)
	if err != nil {
		return true, err
	}
	// If it's a remote node, forward
	if node.Cmp(o.pastry.Self()) != 0 {
		o.fwdBalance(node, msg)
		return true, nil
	}
	// Remove all carrier headers and decrypt
	head := msg.Head.Meta.(*header)
	msg.Head.Meta = head.Meta
	if err := msg.Decrypt(); err != nil {
		return true, err
	}
	// Deliver to the application on the specific topic
	o.app.HandleBalance(head.Sender, topName, msg)
	return true, nil
}
Beispiel #6
0
// Handles the subscription event to a topic.
func (o *Overlay) handleSubscribe(nodeId, topicId *big.Int) error {
	// Generate the textual topic id
	sid := topicId.String()

	// Make sure the requested topic exists, then subscribe
	o.lock.Lock()
	top, ok := o.topics[sid]
	if !ok {
		top = topic.New(topicId, o.pastry.Self())
		o.topics[sid] = top
	}
	o.lock.Unlock()

	// Subscribe node to the topic
	if err := top.Subscribe(nodeId); err != nil {
		return err
	}
	// If a remote node, start monitoring is and respond with an empty report (fast parent discovery)
	if nodeId.Cmp(o.pastry.Self()) != 0 {
		if err := o.monitor(topicId, nodeId); err != nil {
			return err
		}
		rep := &report{
			Tops: []*big.Int{topicId},
			Caps: []int{1},
		}
		o.sendReport(nodeId, rep)
	}
	return nil
}
Beispiel #7
0
// Handles the unsubscription event from a topic.
func (o *Overlay) handleUnsubscribe(nodeId, topicId *big.Int) error {
	o.lock.Lock()
	defer o.lock.Unlock()

	// Fetch the topic and ensure it exists
	sid := topicId.String()
	top, ok := o.topics[sid]
	if !ok {
		return errors.New("non-existent topic")
	}
	// Unsubscribe node from the topic and unmonitor if remote
	if err := top.Unsubscribe(nodeId); err != nil {
		return err
	}
	if nodeId.Cmp(o.pastry.Self()) != 0 {
		if err := o.unmonitor(topicId, nodeId); err != nil {
			return err
		}
	}
	// If topic became empty, send unsubscribe to parent and delete
	if top.Empty() {
		if parent := top.Parent(); parent != nil {
			if err := o.unmonitor(topicId, parent); err != nil {
				return err
			}
			top.Reown(nil)
			go o.sendUnsubscribe(parent, top.Self())
		}
		delete(o.topics, sid)
	}
	return nil
}
Beispiel #8
0
// Test marshaling back and forth between string and int
// Pretty much a sanity check for further tests
func TestStringMarshal(t *testing.T) {
	for _, tc := range idTestCases {
		i := new(big.Int)
		i.SetString(tc.base10, 10)
		assert.Equal(t, tc.base10, i.String())
	}
}
Beispiel #9
0
func compute(count *big.Int) (keys [ResultsPerPage]Key, length int) {
	var padded [32]byte

	var i int
	for i = 0; i < ResultsPerPage; i++ {
		// Increment our counter
		count.Add(count, one)

		// Check to make sure we're not out of range
		if count.Cmp(total) > 0 {
			break
		}

		// Copy count value's bytes to padded slice
		copy(padded[32-len(count.Bytes()):], count.Bytes())

		// Get private and public keys
		privKey, public := btcec.PrivKeyFromBytes(btcec.S256(), padded[:])

		// Get compressed and uncompressed addresses for public key
		caddr, _ := btcutil.NewAddressPubKey(public.SerializeCompressed(), &btcnet.MainNetParams)
		uaddr, _ := btcutil.NewAddressPubKey(public.SerializeUncompressed(), &btcnet.MainNetParams)

		// Encode addresses
		wif, _ := btcutil.NewWIF(privKey, &btcnet.MainNetParams, false)
		keys[i].private = wif.String()
		keys[i].number = count.String()
		keys[i].compressed = caddr.EncodeAddress()
		keys[i].uncompressed = uaddr.EncodeAddress()
	}
	return keys, i
}
Beispiel #10
0
func newPasswd() {
	ClearScreen()
	wr("Make new password\n")

t:
	key := ins("Name of password: "******"" {
		wr("You used an invalid character in your name: ", in)
		goto t
	}
	strlen := ins("Password length: ")
	ig := in("Characters to not include: ")

	ilen, err := strconv.Atoi(strlen)
	if err != nil {
		pause("That wasn't a number")
		return
	}

	passes[key] = NewPass(ilen, ig)

	if Debug {
		fmt.Println("Debug dump:\n\t", passes)
	}

	a, b := big.NewInt(int64(Mod-len(ig))), big.NewInt(int64(ilen))
	var z big.Int
	z.Exp(a, b, nil)
	fmt.Printf("Made new password; Approx chance of guessing = 1/%s\n\n", z.String())
	pause("note that changes have not been saved.")
}
Beispiel #11
0
func main() {

	var count int // initialize count at zero
	distinct_powers := make(map[string]bool)

	for a := 2; a < 101; a++ {
		for b := 2; b < 101; b++ {

			// have to use big.Int because the exponents exceed 20 digits fast
			var ex big.Int
			ex.Exp(big.NewInt(int64(a)), big.NewInt(int64(b)), nil)
			// have to convert back to string because
			// map won't accept big.Int as a key
			term := ex.String()

			if !distinct_powers[term] {
				distinct_powers[term] = true
				count++
			}
		}
	}

	fmt.Println(count)

}
Beispiel #12
0
//插入一个节点
//@node 待插入的节点
func (this *Bucket) InsertNode(node Node) {
	selfInt, _ := new(big.Int).SetString(this.GetRootId(), 10)
	insertInt, _ := new(big.Int).SetString(node.NodeId, 10)
	fmt.Println(node)
	fmt.Println(insertInt.String())
	this.insertLoop(selfInt, insertInt, node)
}
Beispiel #13
0
func main() {
	zaroStr := "0000000000000000000000000000000000000000000000000000000000000000"
	maxNumberStr := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	idStr := "9d1406a76433f43ab752f468e0ca58baf73c9adddfc505a617c5756ea310e44f"
	idInt, _ := new(big.Int).SetString(idStr, 16)
	fmt.Println(len(idStr), len(zaroStr), len(maxNumberStr))

	maxNumberInt, ok := new(big.Int).SetString(maxNumberStr, 16)
	if !ok {
		fmt.Println("失败")
		return
	}

	fmt.Println(maxNumberInt.String(), len(maxNumberInt.String()))
	number_2 := big.NewInt(2)
	halfNumberInt := new(big.Int).Quo(maxNumberInt, number_2)

	fmt.Println(hex.EncodeToString(halfNumberInt.Bytes()))

	halfAndHalfNumberInt := new(big.Int).Quo(halfNumberInt, number_2)
	fmt.Println(hex.EncodeToString(halfAndHalfNumberInt.Bytes()))

	fmt.Println(new(big.Int).Sub(maxNumberInt, idInt))

	// Print(maxNumberInt)

}
Beispiel #14
0
func SendToConn(data []byte, conn *net.TCPConn, path *big.Int) {
	// making variable for combining send data
	var (
		err           tree_lib.TreeError
		path_len_data = make([]byte, 4)
		msg_len_data  = make([]byte, 4)
		path_data     = path.Bytes()
		path_len      = uint32(len(path_data))
		buf           = bytes.Buffer{}
	)

	err.From = tree_lib.FROM_SEND_TO_CONN

	binary.LittleEndian.PutUint32(path_len_data, path_len)
	binary.LittleEndian.PutUint32(msg_len_data, path_len+uint32(len(data))+uint32(4))

	buf.Write(msg_len_data)
	buf.Write(path_len_data)
	buf.Write(path_data)
	buf.Write(data)

	if conn != nil {
		_, err.Err = conn.Write(buf.Bytes())
		if !err.IsNull() {
			tree_log.Error(err.From, fmt.Sprintf("Error sending data to path [%s]", path.String()), err.Error())
		}
	}

	buf.Reset()
}
Beispiel #15
0
// Checks whether a bootstrap-located peer fits into the local routing table or
// will be just discarded anyway.
func (o *Overlay) filter(id *big.Int) bool {
	o.lock.RLock()
	defer o.lock.RUnlock()

	// Discard already connected nodes
	if _, ok := o.livePeers[id.String()]; ok {
		return true
	}

	table := o.routes

	// Check for empty slot in leaf set
	for i, leaf := range table.leaves {
		if leaf.Cmp(o.nodeId) == 0 {
			if delta(id, leaf).Sign() >= 0 && i < config.PastryLeaves/2 {
				return false
			}
			if delta(leaf, id).Sign() >= 0 && len(table.leaves)-i < config.PastryLeaves/2 {
				return false
			}
			break
		}
	}
	// Check for better leaf set
	if delta(table.leaves[0], id).Sign() >= 0 && delta(id, table.leaves[len(table.leaves)-1]).Sign() >= 0 {
		return false
	}
	// Check place in routing table
	pre, col := prefix(o.nodeId, id)
	if prev := table.routes[pre][col]; prev == nil {
		return false
	}
	// Nowhere to insert, bin it
	return true
}
Beispiel #16
0
// Implements the heat.Callback.Dead method, monitoring the death events of
// topic member nodes.
func (o *Overlay) Dead(id *big.Int) {
	// Split the id into topic and node parts
	topic := new(big.Int).Rsh(id, uint(config.PastrySpace))
	node := new(big.Int).Sub(id, new(big.Int).Lsh(topic, uint(config.PastrySpace)))

	log.Printf("scribe: %v topic member death report: %v.", o.pastry.Self(), node)

	o.lock.RLock()
	top, ok := o.topics[topic.String()]
	o.lock.RUnlock()
	if !ok {
		log.Printf("scribe: topic %v already dead.", topic)
		return
	}
	// Depending on whether it was the topic parent or a child reown or unsub
	parent := top.Parent()
	if parent != nil && parent.Cmp(node) == 0 {
		// Make sure it's out of the heartbeat mechanism
		if err := o.heart.Unmonitor(id); err != nil {
			log.Printf("scribe: failed to unmonitor dead parent: %v.", err)
		}
		// Reassign topic rendes-vous point
		top.Reown(nil)
	} else {
		if err := o.handleUnsubscribe(node, topic); err != nil {
			log.Printf("scribe: failed to unsubscribe dead node: %v.", err)
		}
	}
}
Beispiel #17
0
// Forwards a message to the node with the given id and also checks its contents
// if it's a system message.
func (o *Overlay) forward(src *peer, msg *proto.Message, id *big.Int) {
	head := msg.Head.Meta.(*header)
	if head.Op != opNop {
		// Overlay system message, process and forward
		o.process(src, head)
		p, ok := o.livePeers[id.String()]
		o.lock.RUnlock()

		if ok {
			o.send(msg, p)
		}
		return
	}
	// Upper layer message, pass up and check if forward is needed
	o.lock.RUnlock()
	msg.Head.Meta = head.Meta
	allow := o.app.Forward(msg, head.Dest)

	// Forwarding was allowed, repack headers and send
	if allow {
		o.lock.RLock()
		p, ok := o.livePeers[id.String()]
		o.lock.RUnlock()

		if ok {
			head.Meta = msg.Head.Meta
			msg.Head.Meta = head
			o.send(msg, p)
		}
	}
}
Beispiel #18
0
// Returns whether a node is a neighbor of the current one in the topic tree.
func (t *Topic) Neighbor(id *big.Int) bool {
	t.lock.RLock()
	defer t.lock.RUnlock()

	_, ok := t.members[id.String()]
	return ok
}
Beispiel #19
0
func bigDigitSum(n *big.Int) int {
	sum := 0
	for _, c := range n.String() {
		sum += int(c - '0')
	}
	return sum
}
Beispiel #20
0
func main() {

	// Open file for read
	fd, err := os.Open("numbers.txt")
	chk(err)
	defer fd.Close()

	// Line by line reader
	scanner := bufio.NewScanner(fd)
	scanner.Split(bufio.ScanLines)

	// Use standart library - big Integers
	bigSum := new(big.Int)

	for scanner.Scan() {
		ns := scanner.Text()
		bigInt := new(big.Int)
		bigInt.SetString(ns, 10) // Convert readed decimal string to big.Int
		bigSum.Add(bigSum, bigInt)
	}

	answerString := bigSum.String()
	fmt.Println("Result:", answerString, len(answerString))
	fmt.Println("Answer:", answerString[0:10])
}
/* big endian */
func (b *ConstraintBuilder) splitBase(x string, l int, base int64) []string {
	xi := make([]string, l)
	for i := 0; i < l; i++ {
		xi[i] = b.NextVar()
		b.ensureBit(xi[i])
		//        b.addCons(0, []term{term{big.NewInt(1), xi[i]}})
		//        b.addCons(1, []term{term{big.NewInt(1), xi[i]}})
		//        b.addCons(2, []term{term{big.NewInt(1), xi[i]}})
		//b.cmds = append(b.cmds, fmt.Sprintf("P %v = (%v) * (%v) E\n", xi[i], xi[i], xi[i]))
	}

	fmt.Fprintf(b.cmdsFile, "P %v = (", x) // AJF - uncomment
	Ai := make([]term, 0)
	for i := 0; i < l; i++ {
		coef := new(big.Int).Exp(big.NewInt(base), big.NewInt(int64(l-i-1)), nil)
		Ai = append(Ai, term{coef, xi[i]})
		fmt.Fprintf(b.cmdsFile, "%v * %v + ", coef.String(), xi[i]) // AJF - uncomment
	}
	//Ai = append(Ai, term{new(big.Int).Neg(new(big.Int).Exp(big.NewInt(2), big.NewInt(31), nil)), ""})
	//    b.addCons(0, Ai)
	//    b.addCons(1, []term{term{big.NewInt(1), ""}})
	//b.c = append(b.c, []term{term{big.NewInt(1), x},term{new(big.Int).Exp(big.NewInt(2), big.NewInt(31), nil), ""}})
	//    b.addCons(2, []term{term{big.NewInt(1), x}})
	// AJF -    b.cmds = append(b.cmds, fmt.Sprintf("SI %v into %v bits at %v", x, l, xi[0]))
	fmt.Fprintf(b.cmdsFile, "0) * (1) E") // AJF - uncomment

	fmt.Fprintln(b.cmdsFile)
	return xi
}
Beispiel #22
0
func q2() {
	n := new(big.Int)
	a := new(big.Int)
	asquared := new(big.Int)
	one := new(big.Int)
	x := new(big.Int)
	xsquared := new(big.Int)
	p := new(big.Int)
	q := new(big.Int)
	candidate := new(big.Int)

	n.SetString("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 10)
	one.SetString("1", 10)

	a = mathutil.SqrtBig(n)
	for {
		a.Add(a, one)
		asquared.Mul(a, a)
		xsquared.Sub(asquared, n)
		x = mathutil.SqrtBig(xsquared)
		p.Sub(a, x)
		q.Add(a, x)
		if candidate.Mul(p, q).Cmp(n) == 0 {
			fmt.Println(p.String())
			break
		}
	}
}
Beispiel #23
0
// Ported to math/big.Int from github.com/dustin/go-humanize
func Comma(v *big.Int) string {
	{
		var copy big.Int
		copy.Set(v)
		v = &copy
	}
	sign := ""
	if v.Sign() < 0 {
		sign = "-"
		v.Abs(v)
	}

	tmp := &big.Int{}
	herman := big.NewInt(999)
	thousand := big.NewInt(1000)
	var parts []string

	for v.Cmp(herman) > 0 {
		part := tmp.Mod(v, thousand).String()
		switch len(part) {
		case 2:
			part = "0" + part
		case 1:
			part = "00" + part
		}
		v.Div(v, thousand)
		parts = append(parts, part)
	}
	parts = append(parts, v.String())
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}
	return sign + strings.Join(parts, ",")
}
Beispiel #24
0
func SumOfBigIntDigits(n *big.Int) int64 {
	sum := int64(0)
	for _, v := range n.String() {
		sum += int64(RuneToInt(v))
	}
	return sum
}
Beispiel #25
0
func sumDigits(num *big.Int) int {
	sum := 0
	for _, str := range strings.Split(num.String(), "") {
		dig, _ := strconv.Atoi(str)
		sum += dig
	}
	return sum
}
Beispiel #26
0
func digitSum(n *big.Int) int64 {
	var sum int64
	for _, r := range n.String() {
		x, _ := strconv.Atoi(string(r))
		sum += int64(x)
	}
	return sum
}
Beispiel #27
0
Datei: fpd.go Projekt: vadimg/fpd
func bigIntLen(value *big.Int) int {
	// TODO: optimize
	ret := len(value.String())
	if value.Sign() < 0 {
		ret -= 1 // don't count - sign
	}
	return ret
}
Beispiel #28
0
func factorial(n int) string {
	var res big.Int
	res.SetInt64(1)
	for i := 1; i <= n; i++ {
		res.Mul(&res, big.NewInt(int64(i)))
	}
	return res.String()
}
Beispiel #29
0
//得到指定长度的节点id
func RandNodeId(lenght int) string {
	min := rand.New(rand.NewSource(99))
	timens := int64(time.Now().Nanosecond())
	min.Seed(timens)
	maxId := new(big.Int).Lsh(big.NewInt(1), uint(lenght+1))
	randInt := new(big.Int).Rand(min, maxId)
	return randInt.String()
}
// Converts a big.Int into a slice of bytes.
func bigIntToSliceOfBytes(bigInt *big.Int) []byte {
	// Go1.6 introduced the method bigInt.Append() which makes this conversion
	// a lot easier.
	// TODO(erez): Use bigInt.Append() once we switch to GO-1.6.
	result := strconv.AppendQuoteToASCII([]byte{}, bigInt.String())
	// AppendQuoteToASCII adds a double-quoted string. We need to remove them.
	return result[1 : len(result)-1]
}