Author

Topic: Ⓐ Atom - I write crypto currency ✌✌✌ (Read 126 times)

member
Activity: 202
Merit: 27
Atom foundation
8. Creation of a node and joining a new node


I’m tired of testing the data transmission between computers. I’ve created at home a simple local network on the basis of wifi with two ip-addresses and opened ports 5555, via which the nodes will work.
The server (working node or masternode) listens to everything that arrives at port 5555

Code:
from __future__ import print_function

from random import randint
import time
import zmq
import sys
from cl_node import *

node = Node()
context = zmq.Context(1)
server = context.socket(zmq.REP)
server.bind("tcp://*:5555")

cycles = 0
while True:
    request_clear = server.recv()
    request = eval(request_clear.decode())
    if 'wtf' in request:
        print('Work on new transaction')
        print(cycles, ": Normal request (%s)" % str(request))

    if 'addmeplz' in request:
        print('Try add new node')
        node.add_new_node(request['adr'],request['ip'])
        print(cycles, ": Normal request (%s)" % str(request))


    cycles += 1
    # Simulate various problems, after a few cycles
    if cycles > 1000 and randint(0, 1000) == 0:
        print("I: Simulating a crash")
        break
    elif cycles > 1000 and randint(0, 100) == 0:
        print("I: Simulating CPU overload")
        time.sleep(2)

    #time.sleep(1) # Do some heavy work
    send_hash = node.thishash(request_clear).encode()
    print(send_hash)
    server.send(send_hash)

server.close()
context.term()

In this code, we use zeroMQ to get a message on the port, and if there is a code in the message - addmeplz, then we will add a new node to the list of nodes that are responsible for the consensus.
And this is a client who is knocking on the network to join the ranks of the nodes:

Code:
   def try_connect_to_network(self,adr,ipport,base_node):
        context = zmq.Context(1)
        client = context.socket(zmq.REQ)
        SERVER_ENDPOINT = 'tcp://'+base_node
        client.connect(SERVER_ENDPOINT)
        poll = zmq.Poller()
        poll.register(client, zmq.POLLIN)
        REQUEST_TIMEOUT = 2500
        REQUEST_RETRIES = 3
        retries_left = REQUEST_RETRIES

        while retries_left:
            data_send = {'addmeplz': '1','adr': adr, 'ip': ipport}
            data_send = str(data_send).encode()
            request = data_send
            print("I: Пepecылaю (%s)" % request)
            client.send(request)

            expect_reply = True
            while expect_reply:
                socks = dict(poll.poll(REQUEST_TIMEOUT))
                if socks.get(client) == zmq.POLLIN:
                    reply = client.recv()
                    print(reply)
                    print(self.thishash(request))
                    if not reply:
                        break
                    if reply.decode() == self.thishash(request):
                        print("I: Server replied OK (%s)" % reply)
                        retries_left = 0
                        data = 'server get you request'
                        expect_reply = False
                    else:
                        print("E: Malformed reply from server: %s" % reply)

                else:
                    print("W: No response from server, retrying…")
                    # Socket is confused. Close and remove it.
                    client.setsockopt(zmq.LINGER, 0)
                    client.close()
                    poll.unregister(client)
                    retries_left -= 1
                    if retries_left == 0:
                        print("E: Server seems to be offline, abandoning")
                        break
                    print("I: Reconnecting and resending (%s)" % request)
                    # Create new connection
                    client = context.socket(zmq.REQ)
                    client.connect(SERVER_ENDPOINT)
                    poll.register(client, zmq.POLLIN)
                    client.send(request)
        return str(data)

In this case, this is the method that gets the address (node public address), ip and port of the future node (ip should be static), and base_node, this is the address that we are knocking on.
Then it is necessary for the server (masternode) after receiving the message to add a new node to the file with a list of working nodes (the vector of active nodes) and send it to all other nodes for consensus in the list of active nodes (or the vector of active nodes).
member
Activity: 202
Merit: 27
Atom foundation
7. ZeroMQ or sockets on steroids

1. Well, I haven’t written a piece of code yet, because I can’t understand how to make the p2p nodes communicate better. After studying tons of solutions, I came to the conclusion that it's a good idea to use ZeroMQ, since it has a ready-made solution for python as a pyZMQ module.
http://zguide.zeromq.org/py:all - In parallel, I started to translate this article, since there is no guidance on zeromq in Russian, at least a relevant one. The humor of this socket on steroids developer is great, so I find the project quite fun and I’m very glad that it will become a part of the Atom.
2. In parallel, I’m develoing my own consensus algorithm, which is now shaping up to be something similar to the truth, I will describe the principle of its operation a bit later, since it’s of poor design now.
3. the designer joined the Atom project, and we now have a logo, everything is on fun so far and the logo will be on fun https://psv4.userapi.com/c848016/u63431/docs/d3/880bd34f7d0b/asdasdasd.png
the first man who can find the meaning of the logo, will then get atoms.

upd: 19.07.18
member
Activity: 202
Merit: 27
Atom foundation
6. Consensus

The next task is about consensus. We’ve learned to transfer messages and now we have to reinvent the wheel again and create a simple consensus algorithm in the p2p network, in this case between several computers.

It is necessary to:
- agree among the nodes, which transaction will be processed next
- agree on its ordinal number
- check the transaction on each node, record it in the base and create a new block in the chain using our favorite hashing
- exchange the last hashes and confirm the transaction

I’m going to work on the first and second paragraphs now, namely on the achievement of consensus in the number of the next transaction
member
Activity: 202
Merit: 27
Atom foundation
4. Communication p2p. Try to understand

In fact everything is more complicated, I still understand the sockets and how to correctly communicate p2p. HFound a module that is suitable for these tasks, one of them is p2p for etherium
https://github.com/ethereum/pydevp2p
https://github.com/namuyan/p2p-python
http://v0-6.p2p.today/python/tutorial/mesh.html
Oh... my repository  Shocked

Hi!! i tried found you and ask question, but can't found you) and use ZeroMQ finally.
eventually repository get me more idea, thank you!
newbie
Activity: 22
Merit: 0
4. Communication p2p. Try to understand

In fact everything is more complicated, I still understand the sockets and how to correctly communicate p2p. HFound a module that is suitable for these tasks, one of them is p2p for etherium
https://github.com/ethereum/pydevp2p
https://github.com/namuyan/p2p-python
http://v0-6.p2p.today/python/tutorial/mesh.html
Oh... my repository  Shocked
member
Activity: 202
Merit: 27
Atom foundation
5. Socket, socket, they are such sockets

I had to abandon the ready-made python modules that I wrote about earlier, it turned out that either they were buggy, or they had not been updated for many years, or maybe I could not fully understand them, so I had to understand the sockets and send the message peer 2 peer , yourself.

What turned out to be useful, for a thorough understanding
https://docs.python.org/3.4/howto/sockets.html

On the whole, in the dry balance, the code on the python looks like this:
Code:
#!/user/env python3
# -*- coding: utf-8 -*-

import socket
import time
import threading

#
# Ждeм cooбщeния oт нoды 1264
#
def server():
    # cлyшaeм и oтпpaвляeм дaнныe
    s = socket.socket(socket.AF_INET,      # зaдaмeм ceмeйcтвo пpoтoкoлoв 'Интepнeт' (INET)
                          socket.SOCK_STREAM,  # зaдaeм тип пepeдaчи дaнныx 'пoтoкoвый' (TCP)
                          proto=0)
    host = socket.gethostname()
    print(host)
    port = 1264
    s.bind((host, port))

    s.listen(5)


    while True:
        c, addr = s.accept()
        c.send(b'Answer from node 1, adr: ' + str(addr).encode())
        while True:
            # Пoкa клиeнт нe oтключилcя, читaeм пepeдaвaeмыe
            # им дaнныe и oтпpaвляeм иx oбpaтнo
            data = c.recv(1024)
            if not data:
                # Клиeнт oтключилcя
                break
            else:
                print(data.decode())

#
# Oтпpaвляeм cooбщeния нoдe нa 1265 пopтy
#
def client():
    while True:
        s_get = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = socket.gethostname()
        port = 1265
        while True:
            try:
                s_get.connect((host, port))
                break
            except ConnectionRefusedError:
                time.sleep(10)
                print ('Try connect')

        s_get.sendall(b'Msg from node 1')
        data = s_get.recv(1024)
        s_get.close()
        print('Received', repr(data.decode()))
        time.sleep(10)


if __name__ == '__main__':
    my_thread_server = threading.Thread(target=server, args=())
    my_thread_client = threading.Thread(target=client, args=())
    my_thread_server.start()
    my_thread_client.start()

Receiving messages from the node, sending a message to the node and creating two parallel threads.
Now we need to generate a message that will need to be sent, received by another node and processed, and then reach consensus on this information.
member
Activity: 202
Merit: 27
Atom foundation
4. Communication p2p. Try to understand

In fact everything is more complicated, I still understand the sockets and how to correctly communicate p2p. HFound a module that is suitable for these tasks, one of them is p2p for etherium
https://github.com/ethereum/pydevp2p
https://github.com/namuyan/p2p-python
http://v0-6.p2p.today/python/tutorial/mesh.html
member
Activity: 202
Merit: 27
Atom foundation
Great jobs and thank you for sharing this to us but it will all go to waste if people here cannot comprehend what you are trying to get across I recommend that you use this tool https://www.grammarly.com/ or get a help from a friend near your place to help you translate.

it is amazing, good tool, i will try use this, thank you!  Cheesy

after grammarly:
it is amazing, good tool, I will try to use this, thank you!
full member
Activity: 2324
Merit: 175
So basically you are a coder or developer for blockchain based wallets and stuff, im sorry but your english is really hard to understand, still i wish you all the best in your venture.

Hi!
I try write criptocurrency from zero. This is my blog

m sorry but your english is really hard to understand

I understand this and learn English  Wink
may be someone here, could help me with good translate Undecided

Great jobs and thank you for sharing this to us but it will all go to waste if people here cannot comprehend what you are trying to get across I recommend that you use this tool https://www.grammarly.com/ or get a help from a friend near your place to help you translate.
member
Activity: 202
Merit: 27
Atom foundation
3. Dialogue between nodes

Today, the task is to understand the interaction of the nodes for the subsequent communication and the achievement of consensus. It's strange that we need to look for a way to communicate with each other when there is no base with atoms (coins) yet, but we will run a little ahead and then return to creating a base with coins.

Nodes can communicate with each other via ajax or a socket,  and I began to look for the best way to do it. And, of course, the sockets.

Websocket are chosen in two cases:
1. When you need feedback from the server (ie when the server can send you a message yourself, and not only respond to incoming messages)
2. When it is important to have small delays between data transfers.

Actually, it was not necessary to go far, it was worth simply to google, how Bitcoin or Etherium works. (Useful library for understanding || Useful library for understanding 2 - this is all the forks of tool kits written by Vitalik Buterin )

Therefore, we begin to code on the python, a little later I'll take off the code of communication of two nodes.

A good article about sockets - https://medium.com/@dominik.t/what-are-web-sockets-what-about-rest-apis-b9c15fd72aac

ps: sorry for my english, i'm learning  Wink
member
Activity: 202
Merit: 27
Atom foundation
So basically you are a coder or developer for blockchain based wallets and stuff, im sorry but your english is really hard to understand, still i wish you all the best in your venture.

Hi!
I try write criptocurrency from zero. This is my blog

m sorry but your english is really hard to understand

I understand this and learn English  Wink
may be someone here, could help me with good translate Undecided
member
Activity: 1008
Merit: 12
SAPG Pre-Sale Live on Uniswap!
So basically you are a coder or developer for blockchain based wallets and stuff, im sorry but your english is really hard to understand, still i wish you all the best in your venture.
member
Activity: 202
Merit: 27
Atom foundation
2. Password for wallet
        
We created a wallet and password it with the ready Argon2 module. This module is the winner Password Hashing Competition. You can read here - https://password-hashing.net/

When creating a wallet, of course, our goal is maximum security and we will use the latest information on cryptography.

Code:
     
    
        ph = PasswordHasher()
        pwd_hash = ph.hash(pwd)  #pwd
        return pwd_hash

The password check is also very simple
Code:
   
def pass_verify(self,pwd,hash):
        ph = PasswordHasher()
        something = 'pass wrong'
        try:
            val = ph.verify(hash, pwd)
        except:
            return something
        return bool(val)

We can say our raw wallet is ready and meets all the safety requirements:
- Has a pair of keys (public and private)
- The file is password-protected (so you can not just open the file and look at the private key.)

An example of the content of the already working test wallet:

{'privatkey_clear': 'd54d52c4897e0f2fa0408f7fc69d5da917def650a5955011d0f120a053e5a8ca', 'publickey_clear': '06371e9feb37f0698cff4879c4776e6b9c43e71364d9e38fb0ab1146f7e450b38524275fedff05c fd6111fd549b339d1e64e52d30647e9e711afdc6dda308e15', 'publickey_encode': '8D2Pn8JnBwHwotEK9UagWK7YWKVFmZ9XuUzBDA7N9L8GJ1dU74cEJM2v3B7C3uJzeMLosjwG9mSpDdW 1dTEvj96', 'publickey_adress': '4SzkNXVjE9tFhBJWYKLPFfKcqxSY', 'pwd': '$argon2i$v=19$m=512,t=2,p=2$a5LXah3ZmIhFgVuA7fmzVA$s5HtF1u3+DBBtruSDPQ36w'}

member
Activity: 202
Merit: 27
Atom foundation
1. Encryption and electronic signature

The first thing I decided to do was to understand the principle of cryptography, creating a public and private key.
To cudgel one’s brains over something and having spent a lot of time I figured out cryptography and understood the principle of ecdsa. In fact, I began to write code on python, which did one interesting and important thing, created:
private key, public key, password and then saved it to a file

This is the code that selects a point on the curve, then selects the second point on the curve from this point. The second point on the curve is our clear public address from which you will pay or receive a crypt.

Code:
       
        generate_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
        public_key = generate_key.get_verifying_key() # clear key:
        public_key = public_key.to_string().hex()
        private_key = binascii.hexlify(generate_key.to_string()).decode() #privat key: 374bc766d11a59a826249fc42f370cee0518e70925c96e73c1848716216d2f64

In this case, a ready-made solution is used https://github.com/warner/python-ecdsa, so you can be calm for the reliability of the keys you create.

Next, we code the key to make it shorter, here we did not go far and took the principle of creating an address from bitcoin.

Code:
   
    key = base58.b58encode(bytes.fromhex(key))
    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(hashlib.sha256(key.encode()).digest())
    key = base58.b58encode(ripemd160.digest())

After that, we write to the file wallet.pem in the format "key: value" our data (as well as in the wallet Etherium)

Code:
wallet_file_content = {
            "private_key": private_key,
            "public_key": public_key,            
            "publickey_adress": key}
    

        with open('wallet.pem', 'w') as out:
            for key, val in wallet_file_content.items():
                out.write('{}:{}\n'.format(key, val))

A little later I will lay out on the github source code Atom - done
upd (26/05/2018): Cryptographic Right Answers: 2018 - later I will transfer my crypt to NaCl (libsodium)
member
Activity: 202
Merit: 27
Atom foundation


Hi! I write cryptocurrency on Python. I will be writing my blog on this topic about the development of this cryptocurrency. I hope for criticism, feedback and sympathizers, maybe even support.
I from Russia and my English not perfect.  Undecided   I am learning English and also use Grammarly

☆ Target: for fan, blockchain one love
✌ What's the catch: I invent the wheel and a bicycle
♻ Consensus algorithm: hybrid POW (I have one idea and little later I will describe it)
♻ Language of development: Python 3 (lol?)

1. Encryption and electronic signature
2. Password for wallet
3. Dialogue between nodes
4. Communication p2p. Try to understand
5. Socket, socket, they are such sockets
6. Consensus
7. ZeroMQ or sockets on steroids
8. Creation of a node and joining a new node






999. Branch in the Russian community

GitHub | Telegram channel

Jump to: