示例#1
0
文件: setup.py 项目: ehsansh84/ontime
def main():
    tornado.options.parse_command_line()
    db = MongoClient(options.db_host, options.db_port)[options.database]
    name = options.name
    email = options.email
    password = util.hash(str(options.password))
    username = options.username
    user = db.users.find_one({'email': email})
    if user:
        print 'user is exists'
    else:
        db.users.create_index('email', unique=True)
        db.users.create_index('username', unique=True)
        db.users.insert(
            {
                'username': username,
                'name': name,
                'email': email,
                'roles': ['ROLE_ADMIN'],
                'password': password,
                'pic': 'images/profile/default.jpg',
                'activate': True
            }
        )
        print 'user is created'
示例#2
0
def populate_listing(config, asset, listing):
    """Populates a listing with the asset, license and validity information.
    
    config - the configuration to read the listing data from.
    listing - the listing to modify.
    
    Returns an updated listing.
    """
    rval = copy.deepcopy(listing)
    storage_url = config.get("general", "listings-url") + listing["id"]

    rval["id"] = storage_url
    # Set all of the AUTOFILL variables
    if rval.has_key("com:payee"):
        p = rval["com:payee"]
        p["id"] = config.get("general", "listings-url") + p["id"]
        if "AUTOFILL" in p["com:destination"]:
            p["com:destination"] = \
                config.get("application", "financial-account")

    # Set the necessary asset/license variables
    rval["asset"] = asset["id"]
    rval["assetHash"] = util.hash(asset)
    rval["license"] = \
        config.get("application", "default-license")
    rval["licenseHash"] = \
        config.get("application", "default-license-hash")
    rval["validFrom"] = \
        time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    rval["validUntil"] = \
        time.strftime("%Y-%m-%dT%H:%M:%SZ",
            time.gmtime(time.time() + 60*60*24))

    return rval
示例#3
0
    def check_hash(self):
        print("222222222222222222222222222222222222222222222222")
        self._check_hash_counter += 1
        if self._check_hash_counter == 6:
            self.log.info(
                "\nCheck hash brojac i limit za neaktivnost su se poklopili, restartujemo stranu"
            )
            print(
                "\nCheck hash brojac i limit za neaktivnost su se poklopili, restartujemo stranu"
            )
            self.redis.hdel("processed", self.team, self.i)
            self.reload_collector()
        else:
            content_area = self._frame.findFirstElement(
                '#content-all').toPlainText().strip()
            content_hash = util.hash(content_area)

            if self._content_hash == content_hash:
                self._check_hash_counter += 1
                self.log.info("{} sekundi nema promena na prozoru ".format(
                    self._check_hash_counter))
                if self._check_hash_counter == 6:
                    self.log.critical(
                        "Resetujemo prozor, nije bilo promena do zadatog limita"
                    )
                    print(
                        "Resetujemo prozor, nije bilo promena do zadatog limita"
                    )
                    self.redis.hdel("processed", self.team, self.i)
                    self.reload_collector()
            else:
                self._check_hash_counter = 0

            self._content_hash = content_hash
示例#4
0
    def submit_block(self, block, transaction):
        mHash = util.hash(block)

        if self.db.getValue(mHash):
            return False

        if "index" not in block:
            return False
        index = block['index']

        if index == 0:
            if self.hash(block) == FOUNDATIONBLOCK_HASH:
                tran_data = util.getMinerTranscation(
                    util.FOUNDATIONBLOCK_ACCOUNT)
                # self.packagedTransaction.append(tran_data)
                transaction.append(tran_data)
                blockData = {"transactions": transaction, "block": block}
                self.db.putJson(FOUNDATIONBLOCK_HASH, blockData)
                # self.account.append(util.FOUNDATIONBLOCK_ACCOUNT)
                # self.tempAccount.append(util.FOUNDATIONBLOCK_ACCOUNT)
                # print("  初始块  :   " )
                # print(self.db.getValue(FOUNDATIONBLOCK_HASH))
        else:
            beforeBlockInfo = self.db.getValue("block-" + str(index - 1))
            if self.isBlockVaild(beforeBlockInfo, block):
                # self.packagedTransaction.append(util.getMinerTranscation(""))
                blockData = {"transactions": transaction, "block": block}
                # for transaction in transaction:
                #     if(transaction["sender"] !="0"):
                #         self.addTransaction(transaction)
                self.db.putJson(mHash, blockData)
            else:
                return False

        blockInfoKey = "block-" + str(index)
        blockInfo = self.db.getValue(blockInfoKey)

        if not blockInfo:  #
            blockInfo = {
                "index": index,
                "curBlock": mHash,
                "blockpool": [mHash]
            }
        else:
            if mHash not in blockInfo["blockpool"]:
                blockInfo["blockpool"].append(mHash)

        self.db.putJson(blockInfoKey, blockInfo)
        self.index += 1

        # util.output_all_info()
        # util.updateAllAccount(self.tempAccount)

        # self.tempAccount = []
        # for transcation in self.transactionList:
        #     if transcation in self.packagedTransaction:
        #         self.tempAccount.remove(transcation)
        # self.packagedTransaction = []
        settingTran.resetBalance(self)
        return blockData
示例#5
0
def populate_listing(config, asset, listing):
    """Populates a listing with the asset, license and validity information.
    
    config - the configuration to read the listing data from.
    listing - the listing to modify.
    
    Returns an updated listing.
    """
    rval = copy.deepcopy(listing)
    storage_url = config.get("general", "listings-url") + listing["id"]

    rval["id"] = storage_url
    # Set all of the AUTOFILL variables
    if rval.has_key("com:payee"):
        p = rval["com:payee"]
        p["id"] = config.get("general", "listings-url") + p["id"]
        if "AUTOFILL" in p["com:destination"]:
            p["com:destination"] = config.get("application", "financial-account")

    # Set the necessary asset/license variables
    rval["asset"] = asset["id"]
    rval["assetHash"] = util.hash(asset)
    rval["license"] = config.get("application", "default-license")
    rval["licenseHash"] = config.get("application", "default-license-hash")
    rval["validFrom"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    rval["validUntil"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 60 * 60 * 24))

    return rval
示例#6
0
    def create_new_user(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.new_password()
        check_validator(validator)

        user = None
        action = None
        with self.create_storage() as storage:
            by_email = storage.get_user_by_email(email)
            if by_email and by_email.email == email:
                raise servicesexceptions.parameter_error(
                    'email', 'Email is already registered')

            user = User(email, util.hash(password), not self.activate_by_email)

            if self.activate_by_email:
                action = user.enable_action(ActionType.ACTIVATE)

            storage.add(user)

        if self.activate_by_email:
            self.mail.send_activate(self.main_domain, user.email, action.token)

        return user
示例#7
0
def test_hash(algorithm, expected):
    s = ''
    s += algorithm + ':\n'
    s += expected + '\n'
    s += util.hash('', algorithm) + '\n'
    s += '\n'
    return s
示例#8
0
    def isBlockVaild(self, beforeInfo, block):
        if util.hash(block)[:3] != "000":
            return False
        print(beforeInfo)
        if block["previous_hash"] not in beforeInfo["blockpool"]:
            return False

        return True
示例#9
0
 def __initialize(self, firmware_str):
     """
     Initialize firmware based on the binary file
     Arguments:
         firmware_str {String} -- Firmware binary file as string
     """
     self.firmware_hash = u.hash(firmware_str)
     self.IPFS_link = "TBD"
示例#10
0
def on_article(article):
    print(article['url'])
    im = hash(article['image'])
    path = '../reality/data/_images/{}'.format(im)
    faces = extract_faces(path)
    objects = extract_objects(path)
    print('  detected {} faces, {} objects'.format(
        len(faces), len(objects)))
示例#11
0
 def article(self):
     # ugh no reverse lookup, brute force search for now
     files = glob('../reality/data/**/*.json')
     for path in files:
         data = json.load(open(path, 'r'))
         for a in data:
             if hash(a['image']) == self.id:
                 return a
示例#12
0
 def __init__(self, NODES):
     self.NODES = NODES
     self.ring = []
     self.hash2node = {}
     for n in xrange(NODES):
         h = util.hash(n)
         self.ring.append(h)
         self.hash2node[h] = n
     self.ring.sort()
示例#13
0
def test_hash():
    ret = ''
    ret += '\n'
    ret += 'MD5\n'
    ret += util.hash('MD5', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA-128\n'
    ret += util.hash('SHA-1', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA-224\n'
    ret += util.hash('SHA-224', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA-256\n'
    ret += util.hash('SHA-256', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA-384\n'
    ret += util.hash('SHA-384', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA-512\n'
    ret += util.hash('SHA-512', 'abc') + '\n'

    # v3.6+
    ret += '\n'
    ret += 'SHA3-224\n'
    ret += util.hash('SHA3-224', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA3-256\n'
    ret += util.hash('SHA3-256', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA3-384\n'
    ret += util.hash('SHA3-384', 'abc') + '\n'

    ret += '\n'
    ret += 'SHA3-512\n'
    ret += util.hash('SHA3-512', 'abc') + '\n'

    return ret
示例#14
0
    def authenticate(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        check_validator(validator)

        user = self.get_user(email)
        if not user or not user.active or not util.hash(password) == user.password_hash:
            raise servicesexceptions.bad_request('Authentication failed')

        return user
示例#15
0
    def authenticate(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        check_validator(validator)

        user = self.get_user(email)
        if not user or not user.active or not util.hash(
                password) == user.password_hash:
            raise servicesexceptions.bad_request('Authentication failed')

        return user
示例#16
0
    def __post__(self, env, username, email):
        id, code = self.app.request_account(username, email)

        url = util.build_url("/html/registration/%s", config.WEBSITE_URL, id)

        v = view.JSONView(201)
        v.headers["Location"] = url
        v.headers["ETag"] = util.hash(url)
        m = {"Location": url}
        v.bind(m)

        return v
示例#17
0
	def __post__(self, env, username, email):
		id, code = self.app.request_account(username, email)

		url = util.build_url("/html/registration/%s", config.WEBSITE_URL, id)

		v = view.JSONView(201)
		v.headers["Location"] = url
		v.headers["ETag"] = util.hash(url)
		m = {"Location": url}
		v.bind(m)

		return v
示例#18
0
    def rt_hash(self):
        if self._hash is None:
            n = r_uint32(0)
            hash = r_uint32(1)
            for x in range(self._cnt):
                hash = r_uint32(31) * hash + UT.hash(UT.nth(wrap_int(x)))._int_value
                n += 1
                x = RT.next.invoke1(x)

            self._hash = wrap_int(int(mix_col_hash(hash, n)))

        return self._hash
示例#19
0
	def __post__(self, env, username, email):
		id, code = self.app.request_new_password(username, email)

		url = util.build_url("/html/user/%s/password/reset/%s", config.WEBSITE_URL, username, id)

		v = view.JSONView(201)
		v.headers["Location"] = url
		v.headers["ETag"] = util.hash(url)
		m = {"Location": url}
		v.bind(m)

		return v
示例#20
0
    def __post__(self, env, username, email):
        id, code = self.app.request_new_password(username, email)

        url = util.build_url("/html/user/%s/password/reset/%s",
                             config.WEBSITE_URL, username, id)

        v = view.JSONView(201)
        v.headers["Location"] = url
        v.headers["ETag"] = util.hash(url)
        m = {"Location": url}
        v.bind(m)

        return v
示例#21
0
    def rt_hash(self):
        if self._hash is None:
            n = r_uint32(0)
            hash = r_uint32(1)
            for x in range(self._cnt):
                hash = r_uint32(31) * hash + UT.hash(UT.nth(
                    wrap_int(x)))._int_value
                n += 1
                x = RT.next.invoke1(x)

            self._hash = wrap_int(int(mix_col_hash(hash, n)))

        return self._hash
示例#22
0
    def rt_hash(self):
        if self._hash is None:
            n = r_uint32(0)
            hash = r_uint32(1)
            x = RT.seq.invoke1(self)
            while x is not nil:
                hash = r_uint32(31) * hash + UT.hash(UT.first(x))._int_value
                n += 1
                x = RT.next.invoke1(x)

            self._hash = wrap_int(int(mix_col_hash(hash, n)))

        return self._hash
示例#23
0
    def rt_hash(self):
        if self._hash is None:
            n = r_uint32(0)
            hash = r_uint32(1)
            x = RT.seq.invoke1(self)
            while x is not nil:
                hash = r_uint32(31) * hash + UT.hash(UT.first(x))._int_value
                n += 1
                x = RT.next.invoke1(x)


            self._hash = wrap_int(int(mix_col_hash(hash, n)))

        return self._hash
示例#24
0
 def __init__(self, NODES):
     self.NODES = NODES
     self.ring = []
     self.hash2node = {}
     for n in xrange(NODES):
         for vn in xrange(self.VNODES):
             # 根据n和vn简单拼接得到新的独立k
             # 如n=88 vn=99,则拼接得到"0880000000099"
             k = str(n).zfill(3) + str(vn).zfill(10)
             h = util.hash(k)
             self.ring.append(h)
             self.hash2node[h] = n
     self.ring.sort()
     self.ringlen = len(self.ring)
示例#25
0
    def authenticate(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        errors = validator.errors

        if errors:
            message = ", ".join(errors)
            raise servicesexceptions.bad_request(message)

        user = self.get_user(email)
        if not user or not user.active or not util.hash(password) == user.password_hash:
            raise servicesexceptions.forbidden('Authentication failed')

        return user
示例#26
0
    def delete_user(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        check_validator(validator)

        with self.create_storage() as storage:
            user = storage.get_user_by_email(email)

            if not user or not user.active or not util.hash(password) == user.password_hash:
                raise servicesexceptions.bad_request('Authentication failed')

            for domain in user.domains:
                self.dns.delete_domain(self.main_domain, domain)

            storage.delete_user(user)
示例#27
0
    def delete_user(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        check_validator(validator)

        with self.create_storage() as storage:
            user = storage.get_user_by_email(email)

            if not user or not user.active or not util.hash(
                    password) == user.password_hash:
                raise servicesexceptions.bad_request('Authentication failed')

            for domain in user.domains:
                self.dns.delete_domain(self.main_domain, domain)

            storage.delete_user(user)
示例#28
0
    def user_set_password(self, request):
        validator = Validator(request)
        token = validator.token()
        password = validator.new_password()
        check_validator(validator)

        with self.create_storage() as storage:
            user = storage.get_user_by_token(ActionType.PASSWORD, token)

            if not user:
                raise servicesexceptions.bad_request('Invalid password token')

            user.password_hash = util.hash(password)

            self.mail.send_set_password(user.email)

            action = storage.get_action(token)
            storage.delete(action)
示例#29
0
    def user_set_password(self, request):
        validator = Validator(request)
        token = validator.token()
        password = validator.new_password()
        check_validator(validator)

        with self.create_storage() as storage:
            user = storage.get_user_by_token(ActionType.PASSWORD, token)

            if not user:
                raise servicesexceptions.bad_request('Invalid password token')

            user.password_hash = util.hash(password)

            self.mail.send_set_password(user.email)

            action = storage.get_action(token)
            storage.delete(action)
示例#30
0
    def create_new_user(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.password()
        user_domain = validator.new_user_domain(error_if_missing=False)
        errors = validator.errors

        if errors:
            message = ", ".join(errors)
            raise servicesexceptions.bad_request(message)

        user = None
        action = None
        with self.create_storage() as storage:
            by_email = storage.get_user_by_email(email)
            if by_email and by_email.email == email:
                raise servicesexceptions.conflict('Email is already registered')

            if user_domain:
                by_domain = storage.get_domain_by_name(user_domain)
                if by_domain and by_domain.user_domain == user_domain:
                    raise servicesexceptions.conflict('User domain name is already in use')

            update_token = util.create_token()

            user = User(email, util.hash(password), not self.activate_by_email)

            if user_domain:
                domain = Domain(user_domain, None, update_token)
                domain.user = user
                user.domains.append(domain)
                storage.add(domain)

            if self.activate_by_email:
                action = user.enable_action(ActionType.ACTIVATE)

            storage.add(user)

        if self.activate_by_email:
            self.mail.send_activate(self.main_domain, user.email, action.token)

        return user
示例#31
0
 def post(self):
     username = self.get_argument('username')
     password = util.hash(self.get_argument('password'))
     user_model = models.Users(self.db)
     if '@' in username:
         query = {'email': username, 'password': password, 'activate': True}
     else:
         query = {'username': username, 'password': password, 'activate': True}
     user = yield user_model.get(query)
     if not user:
         self.notifications.set('login_error', True)
         self.redirect(self.reverse_url('login'))
         return
     if 'ROLE_ADMIN' in user['roles']:
         self.session.set('user', user)
         self.redirect(self.reverse_url('admin'))
         return
     else:
         self.session.set('user', user)
         self.redirect(self.reverse_url('user'))
         return
示例#32
0
    def user_set_password(self, request):
        validator = Validator(request)
        token = validator.token()
        password = validator.new_password()
        errors = validator.errors

        if errors:
            message = ", ".join(errors)
            raise servicesexceptions.bad_request(message)

        with self.create_storage() as storage:
            user = storage.get_user_by_token(ActionType.PASSWORD, token)

            if not user:
                raise servicesexceptions.forbidden('Invalid password token')

            user.password_hash = util.hash(password)

            self.mail.send_set_password(user.email)

            action = storage.get_action(token)
            storage.delete(action)
示例#33
0
    def create_new_user(self, request):
        validator = Validator(request)
        email = validator.email()
        password = validator.new_password()
        check_validator(validator)

        user = None
        action = None
        with self.create_storage() as storage:
            by_email = storage.get_user_by_email(email)
            if by_email and by_email.email == email:
                raise servicesexceptions.parameter_error('email', 'Email is already registered')

            user = User(email, util.hash(password), not self.activate_by_email)

            if self.activate_by_email:
                action = user.enable_action(ActionType.ACTIVATE)

            storage.add(user)

        if self.activate_by_email:
            self.mail.send_activate(self.main_domain, user.email, action.token)

        return user
示例#34
0
    meta['size'] = canvas.size
    return meta


if __name__ == '__main__':
    from time import sleep
    logging.basicConfig(level=logging.INFO)

    # need to remove guardian images
    # they all have a huge watermark...
    g = glob('{}/data/theguardian.com/*.json'.format(config.REALITY_PATH))
    g_ids = []
    for p in g:
        for a in json.load(open(p, 'r')):
            g_ids.append('{}/data/_images/{}'.format(config.REALITY_PATH,
                                                     util.hash(a['image'])))

    while True:
        misc_images = glob('assets/commons/*')
        news_images = [
            p for p in glob('{}/data/_images/*'.format(config.REALITY_PATH))
            if p not in g_ids
        ]
        logger.info('news images: {}, misc images: {}'.format(
            len(news_images), len(misc_images)))

        paths = random.sample(news_images, config.SAMPLE[0]) + random.sample(
            misc_images, config.SAMPLE[1])
        images = []
        for path in paths:
            try:
示例#35
0
    def post(self):
        action = self.get_argument('action', 'edit')
        if (action == 'create') or (action == 'edit' and unicode(self.current_user['_id']) != self.get_argument('id')):
            if 'ROLE_ADMIN' not in self.current_user['roles']:
                raise tornado.web.HTTPError(401)

        name = self.get_body_argument('name')
        username = self.get_body_argument('username')
        email = self.get_body_argument('email')
        password = self.get_body_argument('password')
        repassword = self.get_body_argument('repassword')
        user_model = models.Users(self.db)
        error = []

        if name == '':
            error.append('name is empty')

        if username == '':
            error.append('username is empty')

        if email == '':
            error.append('email is empty')

        if password == '':
            error.append('password is empty')
        elif password != repassword:
            error.append('password is wrong')
        else:
            password = util.hash(password)

        email_is_exists = yield user_model.get({'email': email})
        if email_is_exists:
            if (action == 'create') or (action == 'edit' and unicode(email_is_exists['_id']) != self.get_argument('id')):
                error.append('This Email Is Registered')

        username_is_exists = yield user_model.get({'username': username})
        if username_is_exists:
            if (action == 'create') or (action == 'edit' and unicode(username_is_exists['_id']) != self.get_argument('id')):
                error.append('This Username Is Registered')

        if action == "create":

            if error:
                self.notifications.set('form_messages', error)
                self.redirect(self.reverse_url('profile') +'?'+ self.request.query)
                return

            pic = self.upload_photo()
            if not pic:
                pic = path('assets', 'images', 'profile', 'default.jpg')

            updated_document = {
                'username': username,
                'name': name,
                'email': email,
                'roles': ["ROLE_USER"], # TODO: Add A Checkbox To Form For Create A Admin
                'password': password,
                'pic': pic
            }

            try:
                res = yield user_model.create(**updated_document)
                message = ['User Is Created']
                self.notifications.set('form_messages', message)

                # if res:
                #     m = R_Mail()
                #     m.from_name = 'Working Hours Activation'
                #     m.from_address = '*****@*****.**'
                #     m.subject = 'User Informations'
                #     m.to = [
                #             {'email': email,'name': name,'type': 'to'}
                #         ]
                #     m.render_html("User_Information.html", username=username, password=self.get_body_argument('password'), host=settings.SERVER_HOST, port=settings.SERVER_PORT)
                #     m.send()
                self.redirect(self.reverse_url('profile') +'?'+ self.request.query)
                return
            except Exception as e:
                print e
                self.notifications.set('form_messages', ['A Exception Is Occur'])
                self.redirect(self.reverse_url('profile') +'?'+ self.request.query)
                return
        else:
            if error:
                self.notifications.set('form_messages', error)
                self.redirect(self.reverse_url('profile') +'?'+ self.request.query)
                return

            id = self.get_argument('id')
            pic = self.upload_photo()

            updated_document = {
                'username': username,
                'name': name,
                'email': email,
                'password': password,
            }

            if pic:
                updated_document['pic'] = pic

            user = yield user_model.update(id, **updated_document)
            if user:
                if id == unicode(self.current_user['_id']):
                    user = yield user_model.get({'_id': id})
                    self.session.set('user', user)
                message = ['User Is Updated']
            else:
                message = ['User Can Not be Update']
            self.notifications.set('form_messages', message)
            self.redirect(self.reverse_url('profile') +'?'+ self.request.query)
            return
示例#36
0
from faces import extract_faces
from objects import extract_objects
from util import hash


def on_article(article):
    print(article['url'])
    im = hash(article['image'])
    path = '../reality/data/_images/{}'.format(im)
    faces = extract_faces(path)
    objects = extract_objects(path)
    print('  detected {} faces, {} objects'.format(
        len(faces), len(objects)))


if __name__ == '__main__':
    while True:
        fifo = 'fifo'
        try:
            with fasteners.InterProcessLock('/tmp/{}.lock'.format(hash(fifo))):
                try:
                    with open(fifo, 'r+') as f:
                        for l in f:
                            article = json.loads(l.strip())
                            on_article(article)
                    open(fifo, 'w').close()
                except FileNotFoundError:
                    print('no fifo')
                sleep(10)
        except (KeyboardInterrupt, SystemExit):
            break
示例#37
0
 def _hash(self):
     strs = [str(self._salt).encode(), self._prev_block_hash.encode()]
     tnxs = [tnx.encode() for tnx in self._transactions]
     return util.hash(strs + tnxs)
示例#38
0
def mine():
    if blockchain.state == "update":
        return "updateing", 200
    # 给工作量证明的节点提供奖励.
    # 发送者为 "0" 表明是新挖出的币
    # blockchain.new_transaction(
    #     sender="0",
    #     recipient=node_identifier,
    #     amount=1,
    # )

    # 生成候选区块
    index = blockchain.index + 1
    gindex = blockchain.globalchainindex + 1
    timestamp = time()
    current_transactions = blockchain.get_transactions_pool()

    last_block = blockchain.last_block
    print("1111111")
    print(last_block)
    previous_hash = util.hash(last_block)

    last_g_block = blockchain.last_gblock
    # previous_g_hash = blockchain.hash( last_g_block )
    previous_g_hash = "4f025c4ef95f64c069dc448b3aef548332f0db12ef7567ff8fa345bd16fe8f11"

    block_tmp = blockchain.new_candidate_block(index,
                                               timestamp,
                                               current_transactions,
                                               previous_hash,
                                               gIndex=gindex,
                                               previous_g_hash=previous_g_hash)

    # 完成工作量证明
    proof = blockchain.proof_of_work(block_tmp)
    block_hash = blockchain.get_hash_block_proof(block_tmp, proof)

    # 生成正式区块
    pinChain = json.load(open('./config/pinChain.json', 'r'))

    # pinChain = json.load(open('./config/pinChain.json', 'r'))
    # gPointer = []
    # for pinName in pinChain:
    #     mhash = requests.get("http://%s/getLastHash" % pinChain[pinName][0])
    #     if mhash:
    #         # print(mhash.json()['hash'])
    #         gPointer.append(mhash.json()['hash'])

    # print("xhxhxhxhxh",gPointer)
    # block = blockchain.new_block(index, timestamp, current_transactions,
    #                          previous_hash, previous_g_hash, gIndex=gindex)
    # payload = json.dumps({"block":block})
    # for pinName in pinChain:
    #     requests.post("http://%s/addGlobalBlock" % pinChain[pinName][0], data = payload)

    # blockchain.globalchainindex += 1

    block = blockchain.new_block(index,
                                 timestamp,
                                 current_transactions,
                                 previous_hash,
                                 proof,
                                 previous_g_hash,
                                 gIndex=gindex)
    print(block)
    response = {
        'message': "New Block Forged",
        'index': block['index'],
        'hash': block_hash,
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    }
    if len(blockchain.transactionList) == 0:
        print("11111")
        blockchain.transactionList.append(
            util.getMinerTranscation(
                "776b95dc71eff9c4ecf5762c46acebdad73e73de"))
    blockData = blockchain.submit_block(block, blockchain.transactionList)
    blockchain.transactionList.clear()
    blockchain.transactionList.append(
        util.getMinerTranscation("776b95dc71eff9c4ecf5762c46acebdad73e73de"))
    print("###############################")
    print(blockData)
    for host in pinChain[blockchain.id]:
        try:
            requests.post("http://%s/submitBlock" % host, json=blockData)
        except:
            pass

    if int(block_hash[:4], 16) <= 8:
        response["message"] = "get global"
        # util.submitGBlockInfo(blockchain, block, [])
        blockData["gpointer"] = []
        print("@193-------------------------------------")
        print(blockData)
        for chain in pinChain:
            for host in pinChain[chain]:
                print(host)
                try:
                    requests.post("http://%s/addGlobalBlock" % host,
                                  json=blockData)
                except:
                    print("fail ----------0")
                    pass

    return jsonify(response), 200
示例#39
0
def writecsv_matrix(datamatrix: m.DataMatrix, filename: str = None):

    list_of_list: List[List[Union[float, str]]] = u.get_classlabeled_list_of_list_from_datamatrix(datamatrix) \
                if datamatrix.classlabels is not None else \
                u.get_list_of_list_from_datamatrix(datamatrix)
    attributes: List[str] or None = copy.deepcopy(
        datamatrix.attributes) if datamatrix.attributes is not None else None

    if attributes is not None:
        attributes.append('class')
        list_of_list.insert(0, attributes)

    if filename is None:
        filename = datamatrix.dataset_name if datamatrix.dataset_name is not None else u.hash(
        )

    filename += '.csv'

    writecsv(filename, list_of_list, directory='output')
示例#40
0
 def _create_client_proxy(self, rpc_channel, request):
     clientid = util.hash(request.SerializeToString())
     client_proxy = ClientProxy(rpc_channel)
     self.proxy_manager.create_client_proxy(clientid, client_proxy)
     return clientid
示例#41
0
 def get_node(self, data):
     h = util.hash(data)
     return h % self.NODES
示例#42
0
    0: 'Zack',
    1: 'Andres',
    2: 'Stephane',
    3: 'Eliza',
    4: 'Sotiris'
}

blockchain_admin = Blockchain_admin(local=True)
m_web3 = blockchain_admin.getWeb3()

# Deploy Contract
cc = Contract('contracts/eduDAO.sol', 'eduDAO', m_web3, verbose=True)
contract = cc.publish(blockchain_admin.get_account(0), 10, 3, 3)
cc.save_abi("contract")
cc.get_consice_instance().addMember(blockchain_admin.get_account(1), "andres",
                                    u.hash("andres"))

for proposal in proposals:
    u1, u2, u3 = random.sample(range(0, 5), 3)
    q1, q2, q3 = random.sample(range(3, 1000), 3)
    total_amount = q1 + q2 + q3
    val = cc.get_def_instance().functions.newProposal([
        blockchain_admin.get_account(u1),
        blockchain_admin.get_account(u2),
        blockchain_admin.get_account(u3)
    ], total_amount, proposal['description'], proposal['course'],
                                                      [q1, q2, q3]).transact()

cc.get_def_instance().functions.vote(0, True, "A string").transact()

print(cc.get_def_instance().functions.getProposalVotes(0).call())
示例#43
0
 def rt_hash(self):
     h = hash_combine(r_uint32(UT.hash(self._name)._int_value), r_uint32(UT.hash(self._ns)._int_value))
     return wrap_int(int(h))
示例#44
0
 def get_node(self, data):
     h = util.hash(data)
     n = bisect_left(self.ring, h) % self.NODES
     return self.hash2node[self.ring[n]]
示例#45
0
 def get_node(self, data):
     h = util.hash(data)
     vn = h % self.VNODES
     return self.ring[vn]