repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.operator | def operator(self):
"""Get the function operator from his name
:return callable: a callable to make operation on a column
"""
operators = (self.op, self.op + '_', '__' + self.op + '__')
for op in operators:
if hasattr(self.column, op):
return op
raise InvalidFilters("{} has no operator {}".format(self.column.key, self.op)) | python | def operator(self):
"""Get the function operator from his name
:return callable: a callable to make operation on a column
"""
operators = (self.op, self.op + '_', '__' + self.op + '__')
for op in operators:
if hasattr(self.column, op):
return op
raise InvalidFilters("{} has no operator {}".format(self.column.key, self.op)) | [
"def",
"operator",
"(",
"self",
")",
":",
"operators",
"=",
"(",
"self",
".",
"op",
",",
"self",
".",
"op",
"+",
"'_'",
",",
"'__'",
"+",
"self",
".",
"op",
"+",
"'__'",
")",
"for",
"op",
"in",
"operators",
":",
"if",
"hasattr",
"(",
"self",
".... | Get the function operator from his name
:return callable: a callable to make operation on a column | [
"Get",
"the",
"function",
"operator",
"from",
"his",
"name"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L112-L123 | train | 224,900 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.value | def value(self):
"""Get the value to filter on
:return: the value to filter on
"""
if self.filter_.get('field') is not None:
try:
result = getattr(self.model, self.filter_['field'])
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, self.filter_['field']))
else:
return result
else:
if 'val' not in self.filter_:
raise InvalidFilters("Can't find value or field in a filter")
return self.filter_['val'] | python | def value(self):
"""Get the value to filter on
:return: the value to filter on
"""
if self.filter_.get('field') is not None:
try:
result = getattr(self.model, self.filter_['field'])
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, self.filter_['field']))
else:
return result
else:
if 'val' not in self.filter_:
raise InvalidFilters("Can't find value or field in a filter")
return self.filter_['val'] | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"filter_",
".",
"get",
"(",
"'field'",
")",
"is",
"not",
"None",
":",
"try",
":",
"result",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"self",
".",
"filter_",
"[",
"'field'",
"]",
")"... | Get the value to filter on
:return: the value to filter on | [
"Get",
"the",
"value",
"to",
"filter",
"on"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L126-L142 | train | 224,901 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_model | def related_model(self):
"""Get the related model of a relationship field
:return DeclarativeMeta: the related model
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return getattr(self.model, get_model_field(self.schema, relationship_field)).property.mapper.class_ | python | def related_model(self):
"""Get the related model of a relationship field
:return DeclarativeMeta: the related model
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return getattr(self.model, get_model_field(self.schema, relationship_field)).property.mapper.class_ | [
"def",
"related_model",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}\... | Get the related model of a relationship field
:return DeclarativeMeta: the related model | [
"Get",
"the",
"related",
"model",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L145-L155 | train | 224,902 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_schema | def related_schema(self):
"""Get the related schema of a relationship field
:return Schema: the related schema
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return self.schema._declared_fields[relationship_field].schema.__class__ | python | def related_schema(self):
"""Get the related schema of a relationship field
:return Schema: the related schema
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return self.schema._declared_fields[relationship_field].schema.__class__ | [
"def",
"related_schema",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}... | Get the related schema of a relationship field
:return Schema: the related schema | [
"Get",
"the",
"related",
"schema",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L158-L168 | train | 224,903 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.init_app | def init_app(self, app=None, blueprint=None, additional_blueprints=None):
"""Update flask application with our api
:param Application app: a flask application
"""
if app is not None:
self.app = app
if blueprint is not None:
self.blueprint = blueprint
for resource in self.resources:
self.route(resource['resource'],
resource['view'],
*resource['urls'],
url_rule_options=resource['url_rule_options'])
if self.blueprint is not None:
self.app.register_blueprint(self.blueprint)
if additional_blueprints is not None:
for blueprint in additional_blueprints:
self.app.register_blueprint(blueprint)
self.app.config.setdefault('PAGE_SIZE', 30) | python | def init_app(self, app=None, blueprint=None, additional_blueprints=None):
"""Update flask application with our api
:param Application app: a flask application
"""
if app is not None:
self.app = app
if blueprint is not None:
self.blueprint = blueprint
for resource in self.resources:
self.route(resource['resource'],
resource['view'],
*resource['urls'],
url_rule_options=resource['url_rule_options'])
if self.blueprint is not None:
self.app.register_blueprint(self.blueprint)
if additional_blueprints is not None:
for blueprint in additional_blueprints:
self.app.register_blueprint(blueprint)
self.app.config.setdefault('PAGE_SIZE', 30) | [
"def",
"init_app",
"(",
"self",
",",
"app",
"=",
"None",
",",
"blueprint",
"=",
"None",
",",
"additional_blueprints",
"=",
"None",
")",
":",
"if",
"app",
"is",
"not",
"None",
":",
"self",
".",
"app",
"=",
"app",
"if",
"blueprint",
"is",
"not",
"None"... | Update flask application with our api
:param Application app: a flask application | [
"Update",
"flask",
"application",
"with",
"our",
"api"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L35-L59 | train | 224,904 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.route | def route(self, resource, view, *urls, **kwargs):
"""Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of the route
"""
resource.view = view
url_rule_options = kwargs.get('url_rule_options') or dict()
view_func = resource.as_view(view)
if 'blueprint' in kwargs:
resource.view = '.'.join([kwargs['blueprint'].name, resource.view])
for url in urls:
kwargs['blueprint'].add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.blueprint is not None:
resource.view = '.'.join([self.blueprint.name, resource.view])
for url in urls:
self.blueprint.add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.app is not None:
for url in urls:
self.app.add_url_rule(url, view_func=view_func, **url_rule_options)
else:
self.resources.append({'resource': resource,
'view': view,
'urls': urls,
'url_rule_options': url_rule_options})
self.resource_registry.append(resource) | python | def route(self, resource, view, *urls, **kwargs):
"""Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of the route
"""
resource.view = view
url_rule_options = kwargs.get('url_rule_options') or dict()
view_func = resource.as_view(view)
if 'blueprint' in kwargs:
resource.view = '.'.join([kwargs['blueprint'].name, resource.view])
for url in urls:
kwargs['blueprint'].add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.blueprint is not None:
resource.view = '.'.join([self.blueprint.name, resource.view])
for url in urls:
self.blueprint.add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.app is not None:
for url in urls:
self.app.add_url_rule(url, view_func=view_func, **url_rule_options)
else:
self.resources.append({'resource': resource,
'view': view,
'urls': urls,
'url_rule_options': url_rule_options})
self.resource_registry.append(resource) | [
"def",
"route",
"(",
"self",
",",
"resource",
",",
"view",
",",
"*",
"urls",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
".",
"view",
"=",
"view",
"url_rule_options",
"=",
"kwargs",
".",
"get",
"(",
"'url_rule_options'",
")",
"or",
"dict",
"(",
")... | Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of the route | [
"Create",
"an",
"api",
"view",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L61-L91 | train | 224,905 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.oauth_manager | def oauth_manager(self, oauth_manager):
"""Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager
"""
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].view_class
if not getattr(resource, 'disable_oauth'):
scopes = request.args.get('scopes')
if getattr(resource, 'schema'):
scopes = [self.build_scope(resource, request.method)]
elif scopes:
scopes = scopes.split(',')
if scopes:
scopes = scopes.split(',')
valid, req = oauth_manager.verify_request(scopes)
for func in oauth_manager._after_request_funcs:
valid, req = func(valid, req)
if not valid:
if oauth_manager._invalid_response:
return oauth_manager._invalid_response(req)
return abort(401)
request.oauth = req | python | def oauth_manager(self, oauth_manager):
"""Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager
"""
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].view_class
if not getattr(resource, 'disable_oauth'):
scopes = request.args.get('scopes')
if getattr(resource, 'schema'):
scopes = [self.build_scope(resource, request.method)]
elif scopes:
scopes = scopes.split(',')
if scopes:
scopes = scopes.split(',')
valid, req = oauth_manager.verify_request(scopes)
for func in oauth_manager._after_request_funcs:
valid, req = func(valid, req)
if not valid:
if oauth_manager._invalid_response:
return oauth_manager._invalid_response(req)
return abort(401)
request.oauth = req | [
"def",
"oauth_manager",
"(",
"self",
",",
"oauth_manager",
")",
":",
"@",
"self",
".",
"app",
".",
"before_request",
"def",
"before_request",
"(",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"resource",
"=",
"self",
".",
"app",
".",
"view_functi... | Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager | [
"Use",
"the",
"oauth",
"manager",
"to",
"enable",
"oauth",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L93-L124 | train | 224,906 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.build_scope | def build_scope(resource, method):
"""Compute the name of the scope for oauth
:param Resource resource: the resource manager
:param str method: an http method
:return str: the name of the scope
"""
if ResourceList in inspect.getmro(resource) and method == 'GET':
prefix = 'list'
else:
method_to_prefix = {'GET': 'get',
'POST': 'create',
'PATCH': 'update',
'DELETE': 'delete'}
prefix = method_to_prefix[method]
if ResourceRelationship in inspect.getmro(resource):
prefix = '_'.join([prefix, 'relationship'])
return '_'.join([prefix, resource.schema.opts.type_]) | python | def build_scope(resource, method):
"""Compute the name of the scope for oauth
:param Resource resource: the resource manager
:param str method: an http method
:return str: the name of the scope
"""
if ResourceList in inspect.getmro(resource) and method == 'GET':
prefix = 'list'
else:
method_to_prefix = {'GET': 'get',
'POST': 'create',
'PATCH': 'update',
'DELETE': 'delete'}
prefix = method_to_prefix[method]
if ResourceRelationship in inspect.getmro(resource):
prefix = '_'.join([prefix, 'relationship'])
return '_'.join([prefix, resource.schema.opts.type_]) | [
"def",
"build_scope",
"(",
"resource",
",",
"method",
")",
":",
"if",
"ResourceList",
"in",
"inspect",
".",
"getmro",
"(",
"resource",
")",
"and",
"method",
"==",
"'GET'",
":",
"prefix",
"=",
"'list'",
"else",
":",
"method_to_prefix",
"=",
"{",
"'GET'",
... | Compute the name of the scope for oauth
:param Resource resource: the resource manager
:param str method: an http method
:return str: the name of the scope | [
"Compute",
"the",
"name",
"of",
"the",
"scope",
"for",
"oauth"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L127-L146 | train | 224,907 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.permission_manager | def permission_manager(self, permission_manager):
"""Use permission manager to enable permission for API
:param callable permission_manager: the permission manager
"""
self.check_permissions = permission_manager
for resource in self.resource_registry:
if getattr(resource, 'disable_permission', None) is not True:
for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):
setattr(resource,
method.lower(),
self.has_permission()(getattr(resource, method.lower()))) | python | def permission_manager(self, permission_manager):
"""Use permission manager to enable permission for API
:param callable permission_manager: the permission manager
"""
self.check_permissions = permission_manager
for resource in self.resource_registry:
if getattr(resource, 'disable_permission', None) is not True:
for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):
setattr(resource,
method.lower(),
self.has_permission()(getattr(resource, method.lower()))) | [
"def",
"permission_manager",
"(",
"self",
",",
"permission_manager",
")",
":",
"self",
".",
"check_permissions",
"=",
"permission_manager",
"for",
"resource",
"in",
"self",
".",
"resource_registry",
":",
"if",
"getattr",
"(",
"resource",
",",
"'disable_permission'",... | Use permission manager to enable permission for API
:param callable permission_manager: the permission manager | [
"Use",
"permission",
"manager",
"to",
"enable",
"permission",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L148-L160 | train | 224,908 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.has_permission | def has_permission(self, *args, **kwargs):
"""Decorator used to check permissions before to call resource manager method"""
def wrapper(view):
if getattr(view, '_has_permissions_decorator', False) is True:
return view
@wraps(view)
@jsonapi_exception_formatter
def decorated(*view_args, **view_kwargs):
self.check_permissions(view, view_args, view_kwargs, *args, **kwargs)
return view(*view_args, **view_kwargs)
decorated._has_permissions_decorator = True
return decorated
return wrapper | python | def has_permission(self, *args, **kwargs):
"""Decorator used to check permissions before to call resource manager method"""
def wrapper(view):
if getattr(view, '_has_permissions_decorator', False) is True:
return view
@wraps(view)
@jsonapi_exception_formatter
def decorated(*view_args, **view_kwargs):
self.check_permissions(view, view_args, view_kwargs, *args, **kwargs)
return view(*view_args, **view_kwargs)
decorated._has_permissions_decorator = True
return decorated
return wrapper | [
"def",
"has_permission",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"view",
")",
":",
"if",
"getattr",
"(",
"view",
",",
"'_has_permissions_decorator'",
",",
"False",
")",
"is",
"True",
":",
"return",
"view... | Decorator used to check permissions before to call resource manager method | [
"Decorator",
"used",
"to",
"check",
"permissions",
"before",
"to",
"call",
"resource",
"manager",
"method"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L162-L175 | train | 224,909 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_headers | def check_headers(func):
"""Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
if request.method in ('POST', 'PATCH'):
if 'Content-Type' in request.headers and\
'application/vnd.api+json' in request.headers['Content-Type'] and\
request.headers['Content-Type'] != 'application/vnd.api+json':
error = json.dumps(jsonapi_errors([{'source': '',
'detail': "Content-Type header must be application/vnd.api+json",
'title': 'Invalid request header',
'status': '415'}]), cls=JSONEncoder)
return make_response(error, 415, {'Content-Type': 'application/vnd.api+json'})
if 'Accept' in request.headers:
flag = False
for accept in request.headers['Accept'].split(','):
if accept.strip() == 'application/vnd.api+json':
flag = False
break
if 'application/vnd.api+json' in accept and accept.strip() != 'application/vnd.api+json':
flag = True
if flag is True:
error = json.dumps(jsonapi_errors([{'source': '',
'detail': ('Accept header must be application/vnd.api+json without'
'media type parameters'),
'title': 'Invalid request header',
'status': '406'}]), cls=JSONEncoder)
return make_response(error, 406, {'Content-Type': 'application/vnd.api+json'})
return func(*args, **kwargs)
return wrapper | python | def check_headers(func):
"""Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
if request.method in ('POST', 'PATCH'):
if 'Content-Type' in request.headers and\
'application/vnd.api+json' in request.headers['Content-Type'] and\
request.headers['Content-Type'] != 'application/vnd.api+json':
error = json.dumps(jsonapi_errors([{'source': '',
'detail': "Content-Type header must be application/vnd.api+json",
'title': 'Invalid request header',
'status': '415'}]), cls=JSONEncoder)
return make_response(error, 415, {'Content-Type': 'application/vnd.api+json'})
if 'Accept' in request.headers:
flag = False
for accept in request.headers['Accept'].split(','):
if accept.strip() == 'application/vnd.api+json':
flag = False
break
if 'application/vnd.api+json' in accept and accept.strip() != 'application/vnd.api+json':
flag = True
if flag is True:
error = json.dumps(jsonapi_errors([{'source': '',
'detail': ('Accept header must be application/vnd.api+json without'
'media type parameters'),
'title': 'Invalid request header',
'status': '406'}]), cls=JSONEncoder)
return make_response(error, 406, {'Content-Type': 'application/vnd.api+json'})
return func(*args, **kwargs)
return wrapper | [
"def",
"check_headers",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PATCH'",
")",
":",
"if",
"'Content-Typ... | Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"headers",
"according",
"to",
"jsonapi",
"reference"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L15-L48 | train | 224,910 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_method_requirements | def check_method_requirements(func):
"""Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
error_message = "You must provide {error_field} in {cls} to get access to the default {method} method"
error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}
if request.method != 'DELETE':
if not hasattr(args[0], 'schema'):
error_data.update({'error_field': 'a schema class'})
raise Exception(error_message.format(**error_data))
return func(*args, **kwargs)
return wrapper | python | def check_method_requirements(func):
"""Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
error_message = "You must provide {error_field} in {cls} to get access to the default {method} method"
error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}
if request.method != 'DELETE':
if not hasattr(args[0], 'schema'):
error_data.update({'error_field': 'a schema class'})
raise Exception(error_message.format(**error_data))
return func(*args, **kwargs)
return wrapper | [
"def",
"check_method_requirements",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"error_message",
"=",
"\"You must provide {error_field} in {cls} to get access to the default {method} met... | Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"methods",
"requirements"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L51-L68 | train | 224,911 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_object | def create_object(self, data, view_kwargs):
"""Create an object through sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_create_object(data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
obj = self.model(**{key: value
for (key, value) in data.items() if key not in join_fields})
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
self.session.add(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})
self.after_create_object(obj, data, view_kwargs)
return obj | python | def create_object(self, data, view_kwargs):
"""Create an object through sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_create_object(data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
obj = self.model(**{key: value
for (key, value) in data.items() if key not in join_fields})
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
self.session.add(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})
self.after_create_object(obj, data, view_kwargs)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"data",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_object",
"(",
"data",
",",
"view_kwargs",
")",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model... | Create an object through sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy | [
"Create",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L38-L69 | train | 224,912 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_object | def get_object(self, view_kwargs, qs=None):
"""Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key)
try:
filter_field = getattr(self.model, id_field)
except Exception:
raise Exception("{} has no attribute {}".format(self.model.__name__, id_field))
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)
if qs is not None:
query = self.eagerload_includes(query, qs)
try:
obj = query.one()
except NoResultFound:
obj = None
self.after_get_object(obj, view_kwargs)
return obj | python | def get_object(self, view_kwargs, qs=None):
"""Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key)
try:
filter_field = getattr(self.model, id_field)
except Exception:
raise Exception("{} has no attribute {}".format(self.model.__name__, id_field))
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)
if qs is not None:
query = self.eagerload_includes(query, qs)
try:
obj = query.one()
except NoResultFound:
obj = None
self.after_get_object(obj, view_kwargs)
return obj | [
"def",
"get_object",
"(",
"self",
",",
"view_kwargs",
",",
"qs",
"=",
"None",
")",
":",
"self",
".",
"before_get_object",
"(",
"view_kwargs",
")",
"id_field",
"=",
"getattr",
"(",
"self",
",",
"'id_field'",
",",
"inspect",
"(",
"self",
".",
"model",
")",... | Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy | [
"Retrieve",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L71-L100 | train | 224,913 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_collection | def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects
"""
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
if qs.sorting:
query = self.sort_query(query, qs.sorting)
object_count = query.count()
if getattr(self, 'eagerload_includes', True):
query = self.eagerload_includes(query, qs)
query = self.paginate_query(query, qs.pagination)
collection = query.all()
collection = self.after_get_collection(collection, qs, view_kwargs)
return object_count, collection | python | def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects
"""
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
if qs.sorting:
query = self.sort_query(query, qs.sorting)
object_count = query.count()
if getattr(self, 'eagerload_includes', True):
query = self.eagerload_includes(query, qs)
query = self.paginate_query(query, qs.pagination)
collection = query.all()
collection = self.after_get_collection(collection, qs, view_kwargs)
return object_count, collection | [
"def",
"get_collection",
"(",
"self",
",",
"qs",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_collection",
"(",
"qs",
",",
"view_kwargs",
")",
"query",
"=",
"self",
".",
"query",
"(",
"view_kwargs",
")",
"if",
"qs",
".",
"filters",
":",
"query"... | Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L102-L130 | train | 224,914 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.update_object | def update_object(self, obj, data, view_kwargs):
"""Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_update_object(obj, data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
for key, value in data.items():
if hasattr(obj, key) and key not in join_fields:
setattr(obj, key, value)
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Update object error: " + str(e), source={'pointer': '/data'})
self.after_update_object(obj, data, view_kwargs) | python | def update_object(self, obj, data, view_kwargs):
"""Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_update_object(obj, data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
for key, value in data.items():
if hasattr(obj, key) and key not in join_fields:
setattr(obj, key, value)
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Update object error: " + str(e), source={'pointer': '/data'})
self.after_update_object(obj, data, view_kwargs) | [
"def",
"update_object",
"(",
"self",
",",
"obj",
",",
"data",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_fiel... | Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False | [
"Update",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L132-L169 | train | 224,915 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_object | def delete_object(self, obj, view_kwargs):
"""Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_delete_object(obj, view_kwargs)
self.session.delete(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete object error: " + str(e))
self.after_delete_object(obj, view_kwargs) | python | def delete_object(self, obj, view_kwargs):
"""Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_delete_object(obj, view_kwargs)
self.session.delete(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete object error: " + str(e))
self.after_delete_object(obj, view_kwargs) | [
"def",
"delete_object",
"(",
"self",
",",
"obj",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"rai... | Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L171-L195 | train | 224,916 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_relationship | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False
"""
self.before_create_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] not in obj_ids:
getattr(obj,
relationship_field).append(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
related_object = None
if json_data['data'] is not None:
related_object = self.get_related_object(related_model, related_id_field, json_data['data'])
obj_id = getattr(getattr(obj, relationship_field), related_id_field, None)
new_obj_id = getattr(related_object, related_id_field, None)
if obj_id != new_obj_id:
setattr(obj, relationship_field, related_object)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Create relationship error: " + str(e))
self.after_create_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | python | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False
"""
self.before_create_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] not in obj_ids:
getattr(obj,
relationship_field).append(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
related_object = None
if json_data['data'] is not None:
related_object = self.get_related_object(related_model, related_id_field, json_data['data'])
obj_id = getattr(getattr(obj, relationship_field), related_id_field, None)
new_obj_id = getattr(related_object, related_id_field, None)
if obj_id != new_obj_id:
setattr(obj, relationship_field, related_object)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Create relationship error: " + str(e))
self.after_create_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | [
"def",
"create_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False | [
"Create",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L197-L254 | train | 224,917 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_relationship | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
"""Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s)
"""
self.before_get_relationship(relationship_field, related_type_, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_objects = getattr(obj, relationship_field)
if related_objects is None:
return obj, related_objects
self.after_get_relationship(obj, related_objects, relationship_field, related_type_, related_id_field,
view_kwargs)
if isinstance(related_objects, InstrumentedList):
return obj,\
[{'type': related_type_, 'id': getattr(obj_, related_id_field)} for obj_ in related_objects]
else:
return obj, {'type': related_type_, 'id': getattr(related_objects, related_id_field)} | python | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
"""Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s)
"""
self.before_get_relationship(relationship_field, related_type_, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_objects = getattr(obj, relationship_field)
if related_objects is None:
return obj, related_objects
self.after_get_relationship(obj, related_objects, relationship_field, related_type_, related_id_field,
view_kwargs)
if isinstance(related_objects, InstrumentedList):
return obj,\
[{'type': related_type_, 'id': getattr(obj_, related_id_field)} for obj_ in related_objects]
else:
return obj, {'type': related_type_, 'id': getattr(related_objects, related_id_field)} | [
"def",
"get_relationship",
"(",
"self",
",",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_relationship",
"(",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view... | Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s) | [
"Get",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L256-L290 | train | 224,918 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_relationship | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
"""
self.before_delete_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] in obj_ids:
getattr(obj,
relationship_field).remove(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
setattr(obj, relationship_field, None)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete relationship error: " + str(e))
self.after_delete_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | python | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
"""
self.before_delete_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] in obj_ids:
getattr(obj,
relationship_field).remove(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
setattr(obj, relationship_field, None)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete relationship error: " + str(e))
self.after_delete_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | [
"def",
"delete_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_delete_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L355-L403 | train | 224,919 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_related_object | def get_related_object(self, related_model, related_id_field, obj):
"""Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object
"""
try:
related_object = self.session.query(related_model)\
.filter(getattr(related_model, related_id_field) == obj['id'])\
.one()
except NoResultFound:
raise RelatedObjectNotFound("{}.{}: {} not found".format(related_model.__name__,
related_id_field,
obj['id']))
return related_object | python | def get_related_object(self, related_model, related_id_field, obj):
"""Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object
"""
try:
related_object = self.session.query(related_model)\
.filter(getattr(related_model, related_id_field) == obj['id'])\
.one()
except NoResultFound:
raise RelatedObjectNotFound("{}.{}: {} not found".format(related_model.__name__,
related_id_field,
obj['id']))
return related_object | [
"def",
"get_related_object",
"(",
"self",
",",
"related_model",
",",
"related_id_field",
",",
"obj",
")",
":",
"try",
":",
"related_object",
"=",
"self",
".",
"session",
".",
"query",
"(",
"related_model",
")",
".",
"filter",
"(",
"getattr",
"(",
"related_mo... | Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object | [
"Get",
"a",
"related",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L405-L422 | train | 224,920 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.apply_relationships | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).property.mapper.class_
schema_field = get_schema_field(self.resource.schema, key)
related_id_field = self.resource.schema._declared_fields[schema_field].id_field
if isinstance(value, list):
related_objects = []
for identifier in value:
related_object = self.get_related_object(related_model, related_id_field, {'id': identifier})
related_objects.append(related_object)
relationships_to_apply.append({'field': key, 'value': related_objects})
else:
related_object = None
if value is not None:
related_object = self.get_related_object(related_model, related_id_field, {'id': value})
relationships_to_apply.append({'field': key, 'value': related_object})
for relationship in relationships_to_apply:
setattr(obj, relationship['field'], relationship['value']) | python | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).property.mapper.class_
schema_field = get_schema_field(self.resource.schema, key)
related_id_field = self.resource.schema._declared_fields[schema_field].id_field
if isinstance(value, list):
related_objects = []
for identifier in value:
related_object = self.get_related_object(related_model, related_id_field, {'id': identifier})
related_objects.append(related_object)
relationships_to_apply.append({'field': key, 'value': related_objects})
else:
related_object = None
if value is not None:
related_object = self.get_related_object(related_model, related_id_field, {'id': value})
relationships_to_apply.append({'field': key, 'value': related_object})
for relationship in relationships_to_apply:
setattr(obj, relationship['field'], relationship['value']) | [
"def",
"apply_relationships",
"(",
"self",
",",
"data",
",",
"obj",
")",
":",
"relationships_to_apply",
"=",
"[",
"]",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"for",
... | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False | [
"Apply",
"relationship",
"provided",
"by",
"data",
"to",
"obj"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L425-L457 | train | 224,921 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.filter_query | def filter_query(self, query, filter_info, model):
"""Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query
"""
if filter_info:
filters = create_filters(model, filter_info, self.resource)
query = query.filter(*filters)
return query | python | def filter_query(self, query, filter_info, model):
"""Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query
"""
if filter_info:
filters = create_filters(model, filter_info, self.resource)
query = query.filter(*filters)
return query | [
"def",
"filter_query",
"(",
"self",
",",
"query",
",",
"filter_info",
",",
"model",
")",
":",
"if",
"filter_info",
":",
"filters",
"=",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"self",
".",
"resource",
")",
"query",
"=",
"query",
".",
"fi... | Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query | [
"Filter",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L490-L503 | train | 224,922 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.sort_query | def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
if not hasattr(self.model, field):
raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
query = query.order_by(getattr(getattr(self.model, field), sort_opt['order'])())
return query | python | def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
if not hasattr(self.model, field):
raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
query = query.order_by(getattr(getattr(self.model, field), sort_opt['order'])())
return query | [
"def",
"sort_query",
"(",
"self",
",",
"query",
",",
"sort_info",
")",
":",
"for",
"sort_opt",
"in",
"sort_info",
":",
"field",
"=",
"sort_opt",
"[",
"'field'",
"]",
"if",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"field",
")",
":",
"raise",
... | Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query | [
"Sort",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L505-L517 | train | 224,923 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.paginate_query | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
return query
page_size = int(paginate_info.get('size', 0)) or current_app.config['PAGE_SIZE']
query = query.limit(page_size)
if paginate_info.get('number'):
query = query.offset((int(paginate_info['number']) - 1) * page_size)
return query | python | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
return query
page_size = int(paginate_info.get('size', 0)) or current_app.config['PAGE_SIZE']
query = query.limit(page_size)
if paginate_info.get('number'):
query = query.offset((int(paginate_info['number']) - 1) * page_size)
return query | [
"def",
"paginate_query",
"(",
"self",
",",
"query",
",",
"paginate_info",
")",
":",
"if",
"int",
"(",
"paginate_info",
".",
"get",
"(",
"'size'",
",",
"1",
")",
")",
"==",
"0",
":",
"return",
"query",
"page_size",
"=",
"int",
"(",
"paginate_info",
".",... | Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query | [
"Paginate",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L519-L534 | train | 224,924 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.eagerload_includes | def eagerload_includes(self, query, qs):
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded
"""
for include in qs.include:
joinload_object = None
if '.' in include:
current_schema = self.resource.schema
for obj in include.split('.'):
try:
field = get_model_field(current_schema, obj)
except Exception as e:
raise InvalidInclude(str(e))
if joinload_object is None:
joinload_object = joinedload(field)
else:
joinload_object = joinload_object.joinedload(field)
related_schema_cls = get_related_schema(current_schema, obj)
if isinstance(related_schema_cls, SchemaABC):
related_schema_cls = related_schema_cls.__class__
else:
related_schema_cls = class_registry.get_class(related_schema_cls)
current_schema = related_schema_cls
else:
try:
field = get_model_field(self.resource.schema, include)
except Exception as e:
raise InvalidInclude(str(e))
joinload_object = joinedload(field)
query = query.options(joinload_object)
return query | python | def eagerload_includes(self, query, qs):
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded
"""
for include in qs.include:
joinload_object = None
if '.' in include:
current_schema = self.resource.schema
for obj in include.split('.'):
try:
field = get_model_field(current_schema, obj)
except Exception as e:
raise InvalidInclude(str(e))
if joinload_object is None:
joinload_object = joinedload(field)
else:
joinload_object = joinload_object.joinedload(field)
related_schema_cls = get_related_schema(current_schema, obj)
if isinstance(related_schema_cls, SchemaABC):
related_schema_cls = related_schema_cls.__class__
else:
related_schema_cls = class_registry.get_class(related_schema_cls)
current_schema = related_schema_cls
else:
try:
field = get_model_field(self.resource.schema, include)
except Exception as e:
raise InvalidInclude(str(e))
joinload_object = joinedload(field)
query = query.options(joinload_object)
return query | [
"def",
"eagerload_includes",
"(",
"self",
",",
"query",
",",
"qs",
")",
":",
"for",
"include",
"in",
"qs",
".",
"include",
":",
"joinload_object",
"=",
"None",
"if",
"'.'",
"in",
"include",
":",
"current_schema",
"=",
"self",
".",
"resource",
".",
"schem... | Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded | [
"Use",
"eagerload",
"feature",
"of",
"sqlalchemy",
"to",
"optimize",
"data",
"retrieval",
"for",
"include",
"querystring",
"parameter"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L536-L577 | train | 224,925 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.retrieve_object_query | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy
"""
return self.session.query(self.model).filter(filter_field == filter_value) | python | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy
"""
return self.session.query(self.model).filter(filter_field == filter_value) | [
"def",
"retrieve_object_query",
"(",
"self",
",",
"view_kwargs",
",",
"filter_field",
",",
"filter_value",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model",
")",
".",
"filter",
"(",
"filter_field",
"==",
"filter_value",
")"... | Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy | [
"Build",
"query",
"to",
"retrieve",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L579-L587 | train | 224,926 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/pagination.py | add_pagination_links | def add_pagination_links(data, object_count, querystring, base_url):
"""Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination
"""
links = {}
all_qs_args = copy(querystring.querystring)
links['self'] = base_url
# compute self link
if all_qs_args:
links['self'] += '?' + urlencode(all_qs_args)
if querystring.pagination.get('size') != '0' and object_count > 1:
# compute last link
page_size = int(querystring.pagination.get('size', 0)) or current_app.config['PAGE_SIZE']
last_page = int(ceil(object_count / page_size))
if last_page > 1:
links['first'] = links['last'] = base_url
all_qs_args.pop('page[number]', None)
# compute first link
if all_qs_args:
links['first'] += '?' + urlencode(all_qs_args)
all_qs_args.update({'page[number]': last_page})
links['last'] += '?' + urlencode(all_qs_args)
# compute previous and next link
current_page = int(querystring.pagination.get('number', 0)) or 1
if current_page > 1:
all_qs_args.update({'page[number]': current_page - 1})
links['prev'] = '?'.join((base_url, urlencode(all_qs_args)))
if current_page < last_page:
all_qs_args.update({'page[number]': current_page + 1})
links['next'] = '?'.join((base_url, urlencode(all_qs_args)))
data['links'] = links | python | def add_pagination_links(data, object_count, querystring, base_url):
"""Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination
"""
links = {}
all_qs_args = copy(querystring.querystring)
links['self'] = base_url
# compute self link
if all_qs_args:
links['self'] += '?' + urlencode(all_qs_args)
if querystring.pagination.get('size') != '0' and object_count > 1:
# compute last link
page_size = int(querystring.pagination.get('size', 0)) or current_app.config['PAGE_SIZE']
last_page = int(ceil(object_count / page_size))
if last_page > 1:
links['first'] = links['last'] = base_url
all_qs_args.pop('page[number]', None)
# compute first link
if all_qs_args:
links['first'] += '?' + urlencode(all_qs_args)
all_qs_args.update({'page[number]': last_page})
links['last'] += '?' + urlencode(all_qs_args)
# compute previous and next link
current_page = int(querystring.pagination.get('number', 0)) or 1
if current_page > 1:
all_qs_args.update({'page[number]': current_page - 1})
links['prev'] = '?'.join((base_url, urlencode(all_qs_args)))
if current_page < last_page:
all_qs_args.update({'page[number]': current_page + 1})
links['next'] = '?'.join((base_url, urlencode(all_qs_args)))
data['links'] = links | [
"def",
"add_pagination_links",
"(",
"data",
",",
"object_count",
",",
"querystring",
",",
"base_url",
")",
":",
"links",
"=",
"{",
"}",
"all_qs_args",
"=",
"copy",
"(",
"querystring",
".",
"querystring",
")",
"links",
"[",
"'self'",
"]",
"=",
"base_url",
"... | Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination | [
"Add",
"pagination",
"links",
"to",
"result"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/pagination.py#L13-L56 | train | 224,927 |
ethereum/py-evm | eth/tools/fixtures/generation.py | idfn | def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names for fixtures.
"""
return ":".join((str(item) for item in fixture_params)) | python | def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names for fixtures.
"""
return ":".join((str(item) for item in fixture_params)) | [
"def",
"idfn",
"(",
"fixture_params",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"str",
":",
"return",
"\":\"",
".",
"join",
"(",
"(",
"str",
"(",
"item",
")",
"for",
"item",
"in",
"fixture_params",
")",
")"
] | Function for pytest to produce uniform names for fixtures. | [
"Function",
"for",
"pytest",
"to",
"produce",
"uniform",
"names",
"for",
"fixtures",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L24-L28 | train | 224,928 |
ethereum/py-evm | eth/tools/fixtures/generation.py | get_fixtures_file_hash | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
"""
Returns the MD5 hash of the fixture files. Used for cache busting.
"""
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixture_file.read())
return hasher.hexdigest() | python | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
"""
Returns the MD5 hash of the fixture files. Used for cache busting.
"""
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixture_file.read())
return hasher.hexdigest() | [
"def",
"get_fixtures_file_hash",
"(",
"all_fixture_paths",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"str",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"fixture_path",
"in",
"sorted",
"(",
"all_fixture_paths",
")",
":",
"with",
"open",
"... | Returns the MD5 hash of the fixture files. Used for cache busting. | [
"Returns",
"the",
"MD5",
"hash",
"of",
"the",
"fixture",
"files",
".",
"Used",
"for",
"cache",
"busting",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L31-L39 | train | 224,929 |
ethereum/py-evm | eth/rlp/transactions.py | BaseTransaction.create_unsigned_transaction | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Create an unsigned transaction.
"""
raise NotImplementedError("Must be implemented by subclasses") | python | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Create an unsigned transaction.
"""
raise NotImplementedError("Must be implemented by subclasses") | [
"def",
"create_unsigned_transaction",
"(",
"cls",
",",
"*",
",",
"nonce",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
")",
"->",
"'BaseUnsignedTransac... | Create an unsigned transaction. | [
"Create",
"an",
"unsigned",
"transaction",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/transactions.py#L155-L166 | train | 224,930 |
ethereum/py-evm | eth/chains/header.py | HeaderChain.import_header | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain.
"""
new_canonical_headers = self.headerdb.persist_header(header)
self.header = self.get_canonical_head()
return new_canonical_headers | python | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain.
"""
new_canonical_headers = self.headerdb.persist_header(header)
self.header = self.get_canonical_head()
return new_canonical_headers | [
"def",
"import_header",
"(",
"self",
",",
"header",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"new_canonical_headers",
"=",
"self",
".",
"header... | Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain. | [
"Direct",
"passthrough",
"to",
"headerdb"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/header.py#L165-L186 | train | 224,931 |
ethereum/py-evm | eth/rlp/headers.py | BlockHeader.from_parent | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
transaction_root: bytes=None,
receipt_root: bytes=None) -> 'BlockHeader':
"""
Initialize a new block header with the `parent` header as the block's
parent hash.
"""
header_kwargs = {
'parent_hash': parent.hash,
'coinbase': coinbase,
'state_root': parent.state_root,
'gas_limit': gas_limit,
'difficulty': difficulty,
'block_number': parent.block_number + 1,
'timestamp': timestamp,
}
if nonce is not None:
header_kwargs['nonce'] = nonce
if extra_data is not None:
header_kwargs['extra_data'] = extra_data
if transaction_root is not None:
header_kwargs['transaction_root'] = transaction_root
if receipt_root is not None:
header_kwargs['receipt_root'] = receipt_root
header = cls(**header_kwargs)
return header | python | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
transaction_root: bytes=None,
receipt_root: bytes=None) -> 'BlockHeader':
"""
Initialize a new block header with the `parent` header as the block's
parent hash.
"""
header_kwargs = {
'parent_hash': parent.hash,
'coinbase': coinbase,
'state_root': parent.state_root,
'gas_limit': gas_limit,
'difficulty': difficulty,
'block_number': parent.block_number + 1,
'timestamp': timestamp,
}
if nonce is not None:
header_kwargs['nonce'] = nonce
if extra_data is not None:
header_kwargs['extra_data'] = extra_data
if transaction_root is not None:
header_kwargs['transaction_root'] = transaction_root
if receipt_root is not None:
header_kwargs['receipt_root'] = receipt_root
header = cls(**header_kwargs)
return header | [
"def",
"from_parent",
"(",
"cls",
",",
"parent",
":",
"'BlockHeader'",
",",
"gas_limit",
":",
"int",
",",
"difficulty",
":",
"int",
",",
"timestamp",
":",
"int",
",",
"coinbase",
":",
"Address",
"=",
"ZERO_ADDRESS",
",",
"nonce",
":",
"bytes",
"=",
"None... | Initialize a new block header with the `parent` header as the block's
parent hash. | [
"Initialize",
"a",
"new",
"block",
"header",
"with",
"the",
"parent",
"header",
"as",
"the",
"block",
"s",
"parent",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/headers.py#L170-L203 | train | 224,932 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_uncles | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
"""
Returns an iterable of uncle headers specified by the given uncles_hash
"""
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
encoded_uncles = self.db[uncles_hash]
except KeyError:
raise HeaderNotFound(
"No uncles found for hash {0}".format(uncles_hash)
)
else:
return rlp.decode(encoded_uncles, sedes=rlp.sedes.CountableList(BlockHeader)) | python | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
"""
Returns an iterable of uncle headers specified by the given uncles_hash
"""
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
encoded_uncles = self.db[uncles_hash]
except KeyError:
raise HeaderNotFound(
"No uncles found for hash {0}".format(uncles_hash)
)
else:
return rlp.decode(encoded_uncles, sedes=rlp.sedes.CountableList(BlockHeader)) | [
"def",
"get_block_uncles",
"(",
"self",
",",
"uncles_hash",
":",
"Hash32",
")",
"->",
"List",
"[",
"BlockHeader",
"]",
":",
"validate_word",
"(",
"uncles_hash",
",",
"title",
"=",
"\"Uncles Hash\"",
")",
"if",
"uncles_hash",
"==",
"EMPTY_UNCLE_HASH",
":",
"ret... | Returns an iterable of uncle headers specified by the given uncles_hash | [
"Returns",
"an",
"iterable",
"of",
"uncle",
"headers",
"specified",
"by",
"the",
"given",
"uncles_hash"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L175-L189 | train | 224,933 |
ethereum/py-evm | eth/db/chain.py | ChainDB.persist_block | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
"""
Persist the given block's header and uncles.
Assumes all block transactions have been persisted already.
"""
with self.db.atomic_batch() as db:
return self._persist_block(db, block) | python | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
"""
Persist the given block's header and uncles.
Assumes all block transactions have been persisted already.
"""
with self.db.atomic_batch() as db:
return self._persist_block(db, block) | [
"def",
"persist_block",
"(",
"self",
",",
"block",
":",
"'BaseBlock'",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
",",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
"]",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")... | Persist the given block's header and uncles.
Assumes all block transactions have been persisted already. | [
"Persist",
"the",
"given",
"block",
"s",
"header",
"and",
"uncles",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L228-L237 | train | 224,934 |
ethereum/py-evm | eth/db/chain.py | ChainDB.persist_uncles | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
"""
Persists the list of uncles to the database.
Returns the uncles hash.
"""
return self._persist_uncles(self.db, uncles) | python | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
"""
Persists the list of uncles to the database.
Returns the uncles hash.
"""
return self._persist_uncles(self.db, uncles) | [
"def",
"persist_uncles",
"(",
"self",
",",
"uncles",
":",
"Tuple",
"[",
"BlockHeader",
"]",
")",
"->",
"Hash32",
":",
"return",
"self",
".",
"_persist_uncles",
"(",
"self",
".",
"db",
",",
"uncles",
")"
] | Persists the list of uncles to the database.
Returns the uncles hash. | [
"Persists",
"the",
"list",
"of",
"uncles",
"to",
"the",
"database",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L273-L279 | train | 224,935 |
ethereum/py-evm | eth/db/chain.py | ChainDB.add_receipt | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
"""
Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_db[index_key] = rlp.encode(receipt)
return receipt_db.root_hash | python | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
"""
Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_db[index_key] = rlp.encode(receipt)
return receipt_db.root_hash | [
"def",
"add_receipt",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"receipt",
":",
"Receipt",
")",
"->",
"Hash32",
":",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"root_hash",
"=",... | Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header. | [
"Adds",
"the",
"given",
"receipt",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L292-L300 | train | 224,936 |
ethereum/py-evm | eth/db/chain.py | ChainDB.add_transaction | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header.
"""
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
transaction_db[index_key] = rlp.encode(transaction)
return transaction_db.root_hash | python | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header.
"""
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
transaction_db[index_key] = rlp.encode(transaction)
return transaction_db.root_hash | [
"def",
"add_transaction",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"transaction",
":",
"'BaseTransaction'",
")",
"->",
"Hash32",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"self",
".",
"db",
",",
"root_hash",... | Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header. | [
"Adds",
"the",
"given",
"transaction",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L302-L313 | train | 224,937 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_transactions | def get_block_transactions(
self,
header: BlockHeader,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Returns an iterable of transactions for the block speficied by the
given block header.
"""
return self._get_block_transactions(header.transaction_root, transaction_class) | python | def get_block_transactions(
self,
header: BlockHeader,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Returns an iterable of transactions for the block speficied by the
given block header.
"""
return self._get_block_transactions(header.transaction_root, transaction_class) | [
"def",
"get_block_transactions",
"(",
"self",
",",
"header",
":",
"BlockHeader",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"Iterable",
"[",
"'BaseTransaction'",
"]",
":",
"return",
"self",
".",
"_get_block_transactions",
"(",... | Returns an iterable of transactions for the block speficied by the
given block header. | [
"Returns",
"an",
"iterable",
"of",
"transactions",
"for",
"the",
"block",
"speficied",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L315-L323 | train | 224,938 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_transaction_hashes | def get_block_transaction_hashes(self, block_header: BlockHeader) -> Iterable[Hash32]:
"""
Returns an iterable of the transaction hashes from the block specified
by the given block header.
"""
return self._get_block_transaction_hashes(self.db, block_header) | python | def get_block_transaction_hashes(self, block_header: BlockHeader) -> Iterable[Hash32]:
"""
Returns an iterable of the transaction hashes from the block specified
by the given block header.
"""
return self._get_block_transaction_hashes(self.db, block_header) | [
"def",
"get_block_transaction_hashes",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
")",
"->",
"Iterable",
"[",
"Hash32",
"]",
":",
"return",
"self",
".",
"_get_block_transaction_hashes",
"(",
"self",
".",
"db",
",",
"block_header",
")"
] | Returns an iterable of the transaction hashes from the block specified
by the given block header. | [
"Returns",
"an",
"iterable",
"of",
"the",
"transaction",
"hashes",
"from",
"the",
"block",
"specified",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L325-L330 | train | 224,939 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_receipts | def get_receipts(self,
header: BlockHeader,
receipt_class: Type[Receipt]) -> Iterable[Receipt]:
"""
Returns an iterable of receipts for the block specified by the given
block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=header.receipt_root)
for receipt_idx in itertools.count():
receipt_key = rlp.encode(receipt_idx)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
yield rlp.decode(receipt_data, sedes=receipt_class)
else:
break | python | def get_receipts(self,
header: BlockHeader,
receipt_class: Type[Receipt]) -> Iterable[Receipt]:
"""
Returns an iterable of receipts for the block specified by the given
block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=header.receipt_root)
for receipt_idx in itertools.count():
receipt_key = rlp.encode(receipt_idx)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
yield rlp.decode(receipt_data, sedes=receipt_class)
else:
break | [
"def",
"get_receipts",
"(",
"self",
",",
"header",
":",
"BlockHeader",
",",
"receipt_class",
":",
"Type",
"[",
"Receipt",
"]",
")",
"->",
"Iterable",
"[",
"Receipt",
"]",
":",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"ro... | Returns an iterable of receipts for the block specified by the given
block header. | [
"Returns",
"an",
"iterable",
"of",
"receipts",
"for",
"the",
"block",
"specified",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L346-L360 | train | 224,940 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_transaction_by_index | def get_transaction_by_index(
self,
block_number: BlockNumber,
transaction_index: int,
transaction_class: Type['BaseTransaction']) -> 'BaseTransaction':
"""
Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise TransactionNotFound("Block {} is not in the canonical chain".format(block_number))
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
encoded_index = rlp.encode(transaction_index)
if encoded_index in transaction_db:
encoded_transaction = transaction_db[encoded_index]
return rlp.decode(encoded_transaction, sedes=transaction_class)
else:
raise TransactionNotFound(
"No transaction is at index {} of block {}".format(transaction_index, block_number)) | python | def get_transaction_by_index(
self,
block_number: BlockNumber,
transaction_index: int,
transaction_class: Type['BaseTransaction']) -> 'BaseTransaction':
"""
Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise TransactionNotFound("Block {} is not in the canonical chain".format(block_number))
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
encoded_index = rlp.encode(transaction_index)
if encoded_index in transaction_db:
encoded_transaction = transaction_db[encoded_index]
return rlp.decode(encoded_transaction, sedes=transaction_class)
else:
raise TransactionNotFound(
"No transaction is at index {} of block {}".format(transaction_index, block_number)) | [
"def",
"get_transaction_by_index",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
",",
"transaction_index",
":",
"int",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"'BaseTransaction'",
":",
"try",
":",
"block_header",
"=... | Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block | [
"Returns",
"the",
"transaction",
"at",
"the",
"specified",
"transaction_index",
"from",
"the",
"block",
"specified",
"by",
"block_number",
"from",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L362-L384 | train | 224,941 |
ethereum/py-evm | eth/db/chain.py | ChainDB.get_receipt_by_index | def get_receipt_by_index(self,
block_number: BlockNumber,
receipt_index: int) -> Receipt:
"""
Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise ReceiptNotFound("Block {} is not in the canonical chain".format(block_number))
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_key = rlp.encode(receipt_index)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
return rlp.decode(receipt_data, sedes=Receipt)
else:
raise ReceiptNotFound(
"Receipt with index {} not found in block".format(receipt_index)) | python | def get_receipt_by_index(self,
block_number: BlockNumber,
receipt_index: int) -> Receipt:
"""
Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise ReceiptNotFound("Block {} is not in the canonical chain".format(block_number))
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_key = rlp.encode(receipt_index)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
return rlp.decode(receipt_data, sedes=Receipt)
else:
raise ReceiptNotFound(
"Receipt with index {} not found in block".format(receipt_index)) | [
"def",
"get_receipt_by_index",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
",",
"receipt_index",
":",
"int",
")",
"->",
"Receipt",
":",
"try",
":",
"block_header",
"=",
"self",
".",
"get_canonical_block_header_by_number",
"(",
"block_number",
")",
"excep... | Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number | [
"Returns",
"the",
"Receipt",
"of",
"the",
"transaction",
"at",
"specified",
"index",
"for",
"the",
"block",
"header",
"obtained",
"by",
"the",
"specified",
"block",
"number"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L405-L424 | train | 224,942 |
ethereum/py-evm | eth/db/chain.py | ChainDB._get_block_transaction_data | def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]:
"""
Returns iterable of the encoded transactions for the given block header
"""
transaction_db = HexaryTrie(db, root_hash=transaction_root)
for transaction_idx in itertools.count():
transaction_key = rlp.encode(transaction_idx)
if transaction_key in transaction_db:
yield transaction_db[transaction_key]
else:
break | python | def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]:
"""
Returns iterable of the encoded transactions for the given block header
"""
transaction_db = HexaryTrie(db, root_hash=transaction_root)
for transaction_idx in itertools.count():
transaction_key = rlp.encode(transaction_idx)
if transaction_key in transaction_db:
yield transaction_db[transaction_key]
else:
break | [
"def",
"_get_block_transaction_data",
"(",
"db",
":",
"BaseDB",
",",
"transaction_root",
":",
"Hash32",
")",
"->",
"Iterable",
"[",
"Hash32",
"]",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"db",
",",
"root_hash",
"=",
"transaction_root",
")",
"for",
"tran... | Returns iterable of the encoded transactions for the given block header | [
"Returns",
"iterable",
"of",
"the",
"encoded",
"transactions",
"for",
"the",
"given",
"block",
"header"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L427-L437 | train | 224,943 |
ethereum/py-evm | eth/db/chain.py | ChainDB._get_block_transactions | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
yield rlp.decode(encoded_transaction, sedes=transaction_class) | python | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
yield rlp.decode(encoded_transaction, sedes=transaction_class) | [
"def",
"_get_block_transactions",
"(",
"self",
",",
"transaction_root",
":",
"Hash32",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"Iterable",
"[",
"'BaseTransaction'",
"]",
":",
"for",
"encoded_transaction",
"in",
"self",
".",... | Memoizable version of `get_block_transactions` | [
"Memoizable",
"version",
"of",
"get_block_transactions"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L441-L449 | train | 224,944 |
ethereum/py-evm | eth/db/chain.py | ChainDB._remove_transaction_from_canonical_chain | def _remove_transaction_from_canonical_chain(db: BaseDB, transaction_hash: Hash32) -> None:
"""
Removes the transaction specified by the given hash from the canonical
chain.
"""
db.delete(SchemaV1.make_transaction_hash_to_block_lookup_key(transaction_hash)) | python | def _remove_transaction_from_canonical_chain(db: BaseDB, transaction_hash: Hash32) -> None:
"""
Removes the transaction specified by the given hash from the canonical
chain.
"""
db.delete(SchemaV1.make_transaction_hash_to_block_lookup_key(transaction_hash)) | [
"def",
"_remove_transaction_from_canonical_chain",
"(",
"db",
":",
"BaseDB",
",",
"transaction_hash",
":",
"Hash32",
")",
"->",
"None",
":",
"db",
".",
"delete",
"(",
"SchemaV1",
".",
"make_transaction_hash_to_block_lookup_key",
"(",
"transaction_hash",
")",
")"
] | Removes the transaction specified by the given hash from the canonical
chain. | [
"Removes",
"the",
"transaction",
"specified",
"by",
"the",
"given",
"hash",
"from",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L452-L457 | train | 224,945 |
ethereum/py-evm | eth/db/chain.py | ChainDB.persist_trie_data_dict | def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None:
"""
Store raw trie data to db from a dict
"""
with self.db.atomic_batch() as db:
for key, value in trie_data_dict.items():
db[key] = value | python | def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None:
"""
Store raw trie data to db from a dict
"""
with self.db.atomic_batch() as db:
for key, value in trie_data_dict.items():
db[key] = value | [
"def",
"persist_trie_data_dict",
"(",
"self",
",",
"trie_data_dict",
":",
"Dict",
"[",
"Hash32",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")",
"as",
"db",
":",
"for",
"key",
",",
"value",
"in",
"... | Store raw trie data to db from a dict | [
"Store",
"raw",
"trie",
"data",
"to",
"db",
"from",
"a",
"dict"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L492-L498 | train | 224,946 |
ethereum/py-evm | eth/vm/forks/frontier/blocks.py | FrontierBlock.from_header | def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock:
"""
Returns the block denoted by the given block header.
"""
if header.uncles_hash == EMPTY_UNCLE_HASH:
uncles = [] # type: List[BlockHeader]
else:
uncles = chaindb.get_block_uncles(header.uncles_hash)
transactions = chaindb.get_block_transactions(header, cls.get_transaction_class())
return cls(
header=header,
transactions=transactions,
uncles=uncles,
) | python | def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock:
"""
Returns the block denoted by the given block header.
"""
if header.uncles_hash == EMPTY_UNCLE_HASH:
uncles = [] # type: List[BlockHeader]
else:
uncles = chaindb.get_block_uncles(header.uncles_hash)
transactions = chaindb.get_block_transactions(header, cls.get_transaction_class())
return cls(
header=header,
transactions=transactions,
uncles=uncles,
) | [
"def",
"from_header",
"(",
"cls",
",",
"header",
":",
"BlockHeader",
",",
"chaindb",
":",
"BaseChainDB",
")",
"->",
"BaseBlock",
":",
"if",
"header",
".",
"uncles_hash",
"==",
"EMPTY_UNCLE_HASH",
":",
"uncles",
"=",
"[",
"]",
"# type: List[BlockHeader]",
"else... | Returns the block denoted by the given block header. | [
"Returns",
"the",
"block",
"denoted",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/blocks.py#L104-L119 | train | 224,947 |
ethereum/py-evm | eth/vm/logic/arithmetic.py | shl | def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0
else:
result = (value << shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | python | def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0
else:
result = (value << shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | [
"def",
"shl",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"shift_length",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"if",
"shift_length",
... | Bitwise left shift | [
"Bitwise",
"left",
"shift"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L186-L197 | train | 224,948 |
ethereum/py-evm | eth/vm/logic/arithmetic.py | sar | def sar(computation: BaseComputation) -> None:
"""
Arithmetic bitwise right shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
value = unsigned_to_signed(value)
if shift_length >= 256:
result = 0 if value >= 0 else constants.UINT_255_NEGATIVE_ONE
else:
result = (value >> shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | python | def sar(computation: BaseComputation) -> None:
"""
Arithmetic bitwise right shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
value = unsigned_to_signed(value)
if shift_length >= 256:
result = 0 if value >= 0 else constants.UINT_255_NEGATIVE_ONE
else:
result = (value >> shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | [
"def",
"sar",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"shift_length",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"value",
"=",
"unsign... | Arithmetic bitwise right shift | [
"Arithmetic",
"bitwise",
"right",
"shift"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L214-L226 | train | 224,949 |
ethereum/py-evm | eth/vm/forks/frontier/headers.py | compute_frontier_difficulty | def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a frontier block based on the parent block.
"""
validate_gt(timestamp, parent_header.timestamp, title="Header timestamp")
offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR
# We set the minimum to the lowest of the protocol minimum and the parent
# minimum to allow for the initial frontier *warming* period during which
# the difficulty begins lower than the protocol minimum.
difficulty_minimum = min(parent_header.difficulty, DIFFICULTY_MINIMUM)
if timestamp - parent_header.timestamp < FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF:
base_difficulty = max(
parent_header.difficulty + offset,
difficulty_minimum,
)
else:
base_difficulty = max(
parent_header.difficulty - offset,
difficulty_minimum,
)
# Adjust for difficulty bomb.
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
difficulty = max(
base_difficulty + 2**num_bomb_periods,
DIFFICULTY_MINIMUM,
)
else:
difficulty = base_difficulty
return difficulty | python | def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a frontier block based on the parent block.
"""
validate_gt(timestamp, parent_header.timestamp, title="Header timestamp")
offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR
# We set the minimum to the lowest of the protocol minimum and the parent
# minimum to allow for the initial frontier *warming* period during which
# the difficulty begins lower than the protocol minimum.
difficulty_minimum = min(parent_header.difficulty, DIFFICULTY_MINIMUM)
if timestamp - parent_header.timestamp < FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF:
base_difficulty = max(
parent_header.difficulty + offset,
difficulty_minimum,
)
else:
base_difficulty = max(
parent_header.difficulty - offset,
difficulty_minimum,
)
# Adjust for difficulty bomb.
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
difficulty = max(
base_difficulty + 2**num_bomb_periods,
DIFFICULTY_MINIMUM,
)
else:
difficulty = base_difficulty
return difficulty | [
"def",
"compute_frontier_difficulty",
"(",
"parent_header",
":",
"BlockHeader",
",",
"timestamp",
":",
"int",
")",
"->",
"int",
":",
"validate_gt",
"(",
"timestamp",
",",
"parent_header",
".",
"timestamp",
",",
"title",
"=",
"\"Header timestamp\"",
")",
"offset",
... | Computes the difficulty for a frontier block based on the parent block. | [
"Computes",
"the",
"difficulty",
"for",
"a",
"frontier",
"block",
"based",
"on",
"the",
"parent",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/headers.py#L36-L73 | train | 224,950 |
ethereum/py-evm | eth/vm/forks/frontier/state.py | FrontierTransactionExecutor.build_computation | def build_computation(self,
message: Message,
transaction: BaseOrSpoofTransaction) -> BaseComputation:
"""Apply the message to the VM."""
transaction_context = self.vm_state.get_transaction_context(transaction)
if message.is_create:
is_collision = self.vm_state.has_code_or_nonce(
message.storage_address
)
if is_collision:
# The address of the newly created contract has *somehow* collided
# with an existing contract address.
computation = self.vm_state.get_computation(message, transaction_context)
computation._error = ContractCreationCollision(
"Address collision while creating contract: {0}".format(
encode_hex(message.storage_address),
)
)
self.vm_state.logger.debug2(
"Address collision while creating contract: %s",
encode_hex(message.storage_address),
)
else:
computation = self.vm_state.get_computation(
message,
transaction_context,
).apply_create_message()
else:
computation = self.vm_state.get_computation(
message,
transaction_context).apply_message()
return computation | python | def build_computation(self,
message: Message,
transaction: BaseOrSpoofTransaction) -> BaseComputation:
"""Apply the message to the VM."""
transaction_context = self.vm_state.get_transaction_context(transaction)
if message.is_create:
is_collision = self.vm_state.has_code_or_nonce(
message.storage_address
)
if is_collision:
# The address of the newly created contract has *somehow* collided
# with an existing contract address.
computation = self.vm_state.get_computation(message, transaction_context)
computation._error = ContractCreationCollision(
"Address collision while creating contract: {0}".format(
encode_hex(message.storage_address),
)
)
self.vm_state.logger.debug2(
"Address collision while creating contract: %s",
encode_hex(message.storage_address),
)
else:
computation = self.vm_state.get_computation(
message,
transaction_context,
).apply_create_message()
else:
computation = self.vm_state.get_computation(
message,
transaction_context).apply_message()
return computation | [
"def",
"build_computation",
"(",
"self",
",",
"message",
":",
"Message",
",",
"transaction",
":",
"BaseOrSpoofTransaction",
")",
"->",
"BaseComputation",
":",
"transaction_context",
"=",
"self",
".",
"vm_state",
".",
"get_transaction_context",
"(",
"transaction",
")... | Apply the message to the VM. | [
"Apply",
"the",
"message",
"to",
"the",
"VM",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/state.py#L107-L140 | train | 224,951 |
ethereum/py-evm | eth/vm/stack.py | Stack.push | def push(self, value: Union[int, bytes]) -> None:
"""
Push an item onto the stack.
"""
if len(self.values) > 1023:
raise FullStack('Stack limit reached')
validate_stack_item(value)
self.values.append(value) | python | def push(self, value: Union[int, bytes]) -> None:
"""
Push an item onto the stack.
"""
if len(self.values) > 1023:
raise FullStack('Stack limit reached')
validate_stack_item(value)
self.values.append(value) | [
"def",
"push",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"int",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"1023",
":",
"raise",
"FullStack",
"(",
"'Stack limit reached'",
")",
"validate_stack_item... | Push an item onto the stack. | [
"Push",
"an",
"item",
"onto",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L38-L47 | train | 224,952 |
ethereum/py-evm | eth/vm/stack.py | Stack.pop | def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return next(self._pop(num_items, type_hint))
else:
return tuple(self._pop(num_items, type_hint))
except IndexError:
raise InsufficientStack("No stack items") | python | def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return next(self._pop(num_items, type_hint))
else:
return tuple(self._pop(num_items, type_hint))
except IndexError:
raise InsufficientStack("No stack items") | [
"def",
"pop",
"(",
"self",
",",
"num_items",
":",
"int",
",",
"type_hint",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"bytes",
",",
"Tuple",
"[",
"Union",
"[",
"int",
",",
"bytes",
"]",
",",
"...",
"]",
"]",
":",
"try",
":",
"if",
"num_it... | Pop an item off the stack.
Note: This function is optimized for speed over readability. | [
"Pop",
"an",
"item",
"off",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L49-L63 | train | 224,953 |
ethereum/py-evm | eth/vm/stack.py | Stack.swap | def swap(self, position: int) -> None:
"""
Perform a SWAP operation on the stack.
"""
idx = -1 * position - 1
try:
self.values[-1], self.values[idx] = self.values[idx], self.values[-1]
except IndexError:
raise InsufficientStack("Insufficient stack items for SWAP{0}".format(position)) | python | def swap(self, position: int) -> None:
"""
Perform a SWAP operation on the stack.
"""
idx = -1 * position - 1
try:
self.values[-1], self.values[idx] = self.values[idx], self.values[-1]
except IndexError:
raise InsufficientStack("Insufficient stack items for SWAP{0}".format(position)) | [
"def",
"swap",
"(",
"self",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"idx",
"=",
"-",
"1",
"*",
"position",
"-",
"1",
"try",
":",
"self",
".",
"values",
"[",
"-",
"1",
"]",
",",
"self",
".",
"values",
"[",
"idx",
"]",
"=",
"self",... | Perform a SWAP operation on the stack. | [
"Perform",
"a",
"SWAP",
"operation",
"on",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L89-L97 | train | 224,954 |
ethereum/py-evm | eth/vm/stack.py | Stack.dup | def dup(self, position: int) -> None:
"""
Perform a DUP operation on the stack.
"""
idx = -1 * position
try:
self.push(self.values[idx])
except IndexError:
raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) | python | def dup(self, position: int) -> None:
"""
Perform a DUP operation on the stack.
"""
idx = -1 * position
try:
self.push(self.values[idx])
except IndexError:
raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) | [
"def",
"dup",
"(",
"self",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"idx",
"=",
"-",
"1",
"*",
"position",
"try",
":",
"self",
".",
"push",
"(",
"self",
".",
"values",
"[",
"idx",
"]",
")",
"except",
"IndexError",
":",
"raise",
"Insuf... | Perform a DUP operation on the stack. | [
"Perform",
"a",
"DUP",
"operation",
"on",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L99-L107 | train | 224,955 |
ethereum/py-evm | eth/db/header.py | HeaderDB.get_canonical_block_hash | def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32:
"""
Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_hash(self.db, block_number) | python | def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32:
"""
Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_hash(self.db, block_number) | [
"def",
"get_canonical_block_hash",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
")",
"->",
"Hash32",
":",
"return",
"self",
".",
"_get_canonical_block_hash",
"(",
"self",
".",
"db",
",",
"block_number",
")"
] | Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain. | [
"Returns",
"the",
"block",
"hash",
"for",
"the",
"canonical",
"block",
"at",
"the",
"given",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L97-L104 | train | 224,956 |
ethereum/py-evm | eth/db/header.py | HeaderDB.get_canonical_block_header_by_number | def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader:
"""
Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_header_by_number(self.db, block_number) | python | def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader:
"""
Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_header_by_number(self.db, block_number) | [
"def",
"get_canonical_block_header_by_number",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
")",
"->",
"BlockHeader",
":",
"return",
"self",
".",
"_get_canonical_block_header_by_number",
"(",
"self",
".",
"db",
",",
"block_number",
")"
] | Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain. | [
"Returns",
"the",
"block",
"header",
"with",
"the",
"given",
"number",
"in",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L120-L127 | train | 224,957 |
ethereum/py-evm | eth/db/header.py | HeaderDB.persist_header_chain | def persist_header_chain(self,
headers: Iterable[BlockHeader]
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers
"""
with self.db.atomic_batch() as db:
return self._persist_header_chain(db, headers) | python | def persist_header_chain(self,
headers: Iterable[BlockHeader]
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers
"""
with self.db.atomic_batch() as db:
return self._persist_header_chain(db, headers) | [
"def",
"persist_header_chain",
"(",
"self",
",",
"headers",
":",
"Iterable",
"[",
"BlockHeader",
"]",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"with",
"self",
".... | Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers | [
"Return",
"two",
"iterable",
"of",
"headers",
"the",
"first",
"containing",
"the",
"new",
"canonical",
"headers",
"the",
"second",
"containing",
"the",
"old",
"canonical",
"headers"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L198-L206 | train | 224,958 |
ethereum/py-evm | eth/db/header.py | HeaderDB._set_as_canonical_chain_head | def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain
"""
try:
header = cls._get_block_header_by_hash(db, block_hash)
except HeaderNotFound:
raise ValueError(
"Cannot use unknown block hash as canonical head: {}".format(block_hash)
)
new_canonical_headers = tuple(reversed(cls._find_new_ancestors(db, header)))
old_canonical_headers = []
for h in new_canonical_headers:
try:
old_canonical_hash = cls._get_canonical_block_hash(db, h.block_number)
except HeaderNotFound:
# no old_canonical block, and no more possible
break
else:
old_canonical_header = cls._get_block_header_by_hash(db, old_canonical_hash)
old_canonical_headers.append(old_canonical_header)
for h in new_canonical_headers:
cls._add_block_number_to_hash_lookup(db, h)
db.set(SchemaV1.make_canonical_head_hash_lookup_key(), header.hash)
return new_canonical_headers, tuple(old_canonical_headers) | python | def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain
"""
try:
header = cls._get_block_header_by_hash(db, block_hash)
except HeaderNotFound:
raise ValueError(
"Cannot use unknown block hash as canonical head: {}".format(block_hash)
)
new_canonical_headers = tuple(reversed(cls._find_new_ancestors(db, header)))
old_canonical_headers = []
for h in new_canonical_headers:
try:
old_canonical_hash = cls._get_canonical_block_hash(db, h.block_number)
except HeaderNotFound:
# no old_canonical block, and no more possible
break
else:
old_canonical_header = cls._get_block_header_by_hash(db, old_canonical_hash)
old_canonical_headers.append(old_canonical_header)
for h in new_canonical_headers:
cls._add_block_number_to_hash_lookup(db, h)
db.set(SchemaV1.make_canonical_head_hash_lookup_key(), header.hash)
return new_canonical_headers, tuple(old_canonical_headers) | [
"def",
"_set_as_canonical_chain_head",
"(",
"cls",
",",
"db",
":",
"BaseDB",
",",
"block_hash",
":",
"Hash32",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"try",
":... | Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain | [
"Sets",
"the",
"canonical",
"chain",
"HEAD",
"to",
"the",
"block",
"header",
"as",
"specified",
"by",
"the",
"given",
"block",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L286-L320 | train | 224,959 |
ethereum/py-evm | eth/db/header.py | HeaderDB._add_block_number_to_hash_lookup | def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None:
"""
Sets a record in the database to allow looking up this header by its
block number.
"""
block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(
header.block_number
)
db.set(
block_number_to_hash_key,
rlp.encode(header.hash, sedes=rlp.sedes.binary),
) | python | def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None:
"""
Sets a record in the database to allow looking up this header by its
block number.
"""
block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(
header.block_number
)
db.set(
block_number_to_hash_key,
rlp.encode(header.hash, sedes=rlp.sedes.binary),
) | [
"def",
"_add_block_number_to_hash_lookup",
"(",
"db",
":",
"BaseDB",
",",
"header",
":",
"BlockHeader",
")",
"->",
"None",
":",
"block_number_to_hash_key",
"=",
"SchemaV1",
".",
"make_block_number_to_hash_lookup_key",
"(",
"header",
".",
"block_number",
")",
"db",
"... | Sets a record in the database to allow looking up this header by its
block number. | [
"Sets",
"a",
"record",
"in",
"the",
"database",
"to",
"allow",
"looking",
"up",
"this",
"header",
"by",
"its",
"block",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L357-L368 | train | 224,960 |
ethereum/py-evm | eth/_utils/headers.py | compute_gas_limit_bounds | def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]:
"""
Compute the boundaries for the block gas limit based on the parent block.
"""
boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
upper_bound = parent.gas_limit + boundary_range
lower_bound = max(GAS_LIMIT_MINIMUM, parent.gas_limit - boundary_range)
return lower_bound, upper_bound | python | def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]:
"""
Compute the boundaries for the block gas limit based on the parent block.
"""
boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
upper_bound = parent.gas_limit + boundary_range
lower_bound = max(GAS_LIMIT_MINIMUM, parent.gas_limit - boundary_range)
return lower_bound, upper_bound | [
"def",
"compute_gas_limit_bounds",
"(",
"parent",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"boundary_range",
"=",
"parent",
".",
"gas_limit",
"//",
"GAS_LIMIT_ADJUSTMENT_FACTOR",
"upper_bound",
"=",
"parent",
".",
"gas_limit",
"+... | Compute the boundaries for the block gas limit based on the parent block. | [
"Compute",
"the",
"boundaries",
"for",
"the",
"block",
"gas",
"limit",
"based",
"on",
"the",
"parent",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L20-L27 | train | 224,961 |
ethereum/py-evm | eth/_utils/headers.py | compute_gas_limit | def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int:
"""
A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit.
"""
if gas_limit_floor < GAS_LIMIT_MINIMUM:
raise ValueError(
"The `gas_limit_floor` value must be greater than the "
"GAS_LIMIT_MINIMUM. Got {0}. Must be greater than "
"{1}".format(gas_limit_floor, GAS_LIMIT_MINIMUM)
)
decay = parent_header.gas_limit // GAS_LIMIT_EMA_DENOMINATOR
if parent_header.gas_used:
usage_increase = (
parent_header.gas_used * GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR
) // (
GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR
) // (
GAS_LIMIT_EMA_DENOMINATOR
)
else:
usage_increase = 0
gas_limit = max(
GAS_LIMIT_MINIMUM,
parent_header.gas_limit - decay + usage_increase
)
if gas_limit < GAS_LIMIT_MINIMUM:
return GAS_LIMIT_MINIMUM
elif gas_limit < gas_limit_floor:
return parent_header.gas_limit + decay
else:
return gas_limit | python | def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int:
"""
A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit.
"""
if gas_limit_floor < GAS_LIMIT_MINIMUM:
raise ValueError(
"The `gas_limit_floor` value must be greater than the "
"GAS_LIMIT_MINIMUM. Got {0}. Must be greater than "
"{1}".format(gas_limit_floor, GAS_LIMIT_MINIMUM)
)
decay = parent_header.gas_limit // GAS_LIMIT_EMA_DENOMINATOR
if parent_header.gas_used:
usage_increase = (
parent_header.gas_used * GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR
) // (
GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR
) // (
GAS_LIMIT_EMA_DENOMINATOR
)
else:
usage_increase = 0
gas_limit = max(
GAS_LIMIT_MINIMUM,
parent_header.gas_limit - decay + usage_increase
)
if gas_limit < GAS_LIMIT_MINIMUM:
return GAS_LIMIT_MINIMUM
elif gas_limit < gas_limit_floor:
return parent_header.gas_limit + decay
else:
return gas_limit | [
"def",
"compute_gas_limit",
"(",
"parent_header",
":",
"BlockHeader",
",",
"gas_limit_floor",
":",
"int",
")",
"->",
"int",
":",
"if",
"gas_limit_floor",
"<",
"GAS_LIMIT_MINIMUM",
":",
"raise",
"ValueError",
"(",
"\"The `gas_limit_floor` value must be greater than the \""... | A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit. | [
"A",
"simple",
"strategy",
"for",
"adjusting",
"the",
"gas",
"limit",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L30-L77 | train | 224,962 |
ethereum/py-evm | eth/_utils/headers.py | generate_header_from_parent_header | def generate_header_from_parent_header(
compute_difficulty_fn: Callable[[BlockHeader, int], int],
parent_header: BlockHeader,
coinbase: Address,
timestamp: Optional[int] = None,
extra_data: bytes = b'') -> BlockHeader:
"""
Generate BlockHeader from state_root and parent_header
"""
if timestamp is None:
timestamp = max(int(time.time()), parent_header.timestamp + 1)
elif timestamp <= parent_header.timestamp:
raise ValueError(
"header.timestamp ({}) should be higher than"
"parent_header.timestamp ({})".format(
timestamp,
parent_header.timestamp,
)
)
header = BlockHeader(
difficulty=compute_difficulty_fn(parent_header, timestamp),
block_number=(parent_header.block_number + 1),
gas_limit=compute_gas_limit(
parent_header,
gas_limit_floor=GENESIS_GAS_LIMIT,
),
timestamp=timestamp,
parent_hash=parent_header.hash,
state_root=parent_header.state_root,
coinbase=coinbase,
extra_data=extra_data,
)
return header | python | def generate_header_from_parent_header(
compute_difficulty_fn: Callable[[BlockHeader, int], int],
parent_header: BlockHeader,
coinbase: Address,
timestamp: Optional[int] = None,
extra_data: bytes = b'') -> BlockHeader:
"""
Generate BlockHeader from state_root and parent_header
"""
if timestamp is None:
timestamp = max(int(time.time()), parent_header.timestamp + 1)
elif timestamp <= parent_header.timestamp:
raise ValueError(
"header.timestamp ({}) should be higher than"
"parent_header.timestamp ({})".format(
timestamp,
parent_header.timestamp,
)
)
header = BlockHeader(
difficulty=compute_difficulty_fn(parent_header, timestamp),
block_number=(parent_header.block_number + 1),
gas_limit=compute_gas_limit(
parent_header,
gas_limit_floor=GENESIS_GAS_LIMIT,
),
timestamp=timestamp,
parent_hash=parent_header.hash,
state_root=parent_header.state_root,
coinbase=coinbase,
extra_data=extra_data,
)
return header | [
"def",
"generate_header_from_parent_header",
"(",
"compute_difficulty_fn",
":",
"Callable",
"[",
"[",
"BlockHeader",
",",
"int",
"]",
",",
"int",
"]",
",",
"parent_header",
":",
"BlockHeader",
",",
"coinbase",
":",
"Address",
",",
"timestamp",
":",
"Optional",
"... | Generate BlockHeader from state_root and parent_header | [
"Generate",
"BlockHeader",
"from",
"state_root",
"and",
"parent_header"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L80-L113 | train | 224,963 |
ethereum/py-evm | eth/tools/_utils/normalization.py | state_definition_to_dict | def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
"""Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
```
"""
if isinstance(state_definition, Mapping):
state_dict = state_definition
elif isinstance(state_definition, Iterable):
state_dicts = [
assoc_in(
{},
state_item[:-1],
state_item[-1]
) if not isinstance(state_item, Mapping) else state_item
for state_item
in state_definition
]
if not is_cleanly_mergable(*state_dicts):
raise ValidationError("Some state item is defined multiple times")
state_dict = deep_merge(*state_dicts)
else:
assert TypeError("State definition must either be a mapping or a sequence")
seen_keys = set(concat(d.keys() for d in state_dict.values()))
bad_keys = seen_keys - set(["balance", "nonce", "storage", "code"])
if bad_keys:
raise ValidationError(
"State definition contains the following invalid account fields: {}".format(
", ".join(bad_keys)
)
)
return state_dict | python | def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
"""Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
```
"""
if isinstance(state_definition, Mapping):
state_dict = state_definition
elif isinstance(state_definition, Iterable):
state_dicts = [
assoc_in(
{},
state_item[:-1],
state_item[-1]
) if not isinstance(state_item, Mapping) else state_item
for state_item
in state_definition
]
if not is_cleanly_mergable(*state_dicts):
raise ValidationError("Some state item is defined multiple times")
state_dict = deep_merge(*state_dicts)
else:
assert TypeError("State definition must either be a mapping or a sequence")
seen_keys = set(concat(d.keys() for d in state_dict.values()))
bad_keys = seen_keys - set(["balance", "nonce", "storage", "code"])
if bad_keys:
raise ValidationError(
"State definition contains the following invalid account fields: {}".format(
", ".join(bad_keys)
)
)
return state_dict | [
"def",
"state_definition_to_dict",
"(",
"state_definition",
":",
"GeneralState",
")",
"->",
"AccountState",
":",
"if",
"isinstance",
"(",
"state_definition",
",",
"Mapping",
")",
":",
"state_dict",
"=",
"state_definition",
"elif",
"isinstance",
"(",
"state_definition"... | Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
``` | [
"Convert",
"a",
"state",
"definition",
"to",
"the",
"canonical",
"dict",
"form",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L183-L231 | train | 224,964 |
ethereum/py-evm | eth/db/journal.py | Journal.record_changeset | def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets.
"""
if custom_changeset_id is not None:
if custom_changeset_id in self.journal_data:
raise ValidationError(
"Tried to record with an existing changeset id: %r" % custom_changeset_id
)
else:
changeset_id = custom_changeset_id
else:
changeset_id = uuid.uuid4()
self.journal_data[changeset_id] = {}
return changeset_id | python | def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets.
"""
if custom_changeset_id is not None:
if custom_changeset_id in self.journal_data:
raise ValidationError(
"Tried to record with an existing changeset id: %r" % custom_changeset_id
)
else:
changeset_id = custom_changeset_id
else:
changeset_id = uuid.uuid4()
self.journal_data[changeset_id] = {}
return changeset_id | [
"def",
"record_changeset",
"(",
"self",
",",
"custom_changeset_id",
":",
"uuid",
".",
"UUID",
"=",
"None",
")",
"->",
"uuid",
".",
"UUID",
":",
"if",
"custom_changeset_id",
"is",
"not",
"None",
":",
"if",
"custom_changeset_id",
"in",
"self",
".",
"journal_da... | Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets. | [
"Creates",
"a",
"new",
"changeset",
".",
"Changesets",
"are",
"referenced",
"by",
"a",
"random",
"uuid4",
"to",
"prevent",
"collisions",
"between",
"multiple",
"changesets",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L93-L109 | train | 224,965 |
ethereum/py-evm | eth/db/journal.py | Journal.pop_changeset | def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
if changeset_id not in self.journal_data:
raise KeyError(changeset_id, "Unknown changeset in JournalDB")
all_ids = tuple(self.journal_data.keys())
changeset_idx = all_ids.index(changeset_id)
changesets_to_pop = all_ids[changeset_idx:]
popped_clears = tuple(idx for idx in changesets_to_pop if idx in self._clears_at)
if popped_clears:
last_clear_idx = changesets_to_pop.index(popped_clears[-1])
changesets_to_drop = changesets_to_pop[:last_clear_idx]
changesets_to_merge = changesets_to_pop[last_clear_idx:]
else:
changesets_to_drop = ()
changesets_to_merge = changesets_to_pop
# we pull all of the changesets *after* the changeset we are
# reverting to and collapse them to a single set of keys (giving
# precedence to later changesets)
changeset_data = merge(*(
self.journal_data.pop(c_id)
for c_id
in changesets_to_merge
))
# drop the changes on the floor if they came before a clear that is being committed
for changeset_id in changesets_to_drop:
self.journal_data.pop(changeset_id)
self._clears_at.difference_update(popped_clears)
return changeset_data | python | def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
if changeset_id not in self.journal_data:
raise KeyError(changeset_id, "Unknown changeset in JournalDB")
all_ids = tuple(self.journal_data.keys())
changeset_idx = all_ids.index(changeset_id)
changesets_to_pop = all_ids[changeset_idx:]
popped_clears = tuple(idx for idx in changesets_to_pop if idx in self._clears_at)
if popped_clears:
last_clear_idx = changesets_to_pop.index(popped_clears[-1])
changesets_to_drop = changesets_to_pop[:last_clear_idx]
changesets_to_merge = changesets_to_pop[last_clear_idx:]
else:
changesets_to_drop = ()
changesets_to_merge = changesets_to_pop
# we pull all of the changesets *after* the changeset we are
# reverting to and collapse them to a single set of keys (giving
# precedence to later changesets)
changeset_data = merge(*(
self.journal_data.pop(c_id)
for c_id
in changesets_to_merge
))
# drop the changes on the floor if they came before a clear that is being committed
for changeset_id in changesets_to_drop:
self.journal_data.pop(changeset_id)
self._clears_at.difference_update(popped_clears)
return changeset_data | [
"def",
"pop_changeset",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"Dict",
"[",
"bytes",
",",
"Union",
"[",
"bytes",
",",
"DeletedEntry",
"]",
"]",
":",
"if",
"changeset_id",
"not",
"in",
"self",
".",
"journal_data",
":",
"r... | Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets. | [
"Returns",
"all",
"changes",
"from",
"the",
"given",
"changeset",
".",
"This",
"includes",
"all",
"of",
"the",
"changes",
"from",
"any",
"subsequent",
"changeset",
"giving",
"precidence",
"to",
"later",
"changesets",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L111-L146 | train | 224,966 |
ethereum/py-evm | eth/db/journal.py | Journal.commit_changeset | def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Collapses all changes for the given changeset into the previous
changesets if it exists.
"""
does_clear = self.has_clear(changeset_id)
changeset_data = self.pop_changeset(changeset_id)
if not self.is_empty():
# we only have to assign changeset data into the latest changeset if
# there is one.
if does_clear:
# if there was a clear and more changesets underneath then clear the latest
# changeset, and replace with a new clear changeset
self.latest = {}
self._clears_at.add(self.latest_id)
self.record_changeset()
self.latest = changeset_data
else:
# otherwise, merge in all the current data
self.latest = merge(
self.latest,
changeset_data,
)
return changeset_data | python | def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Collapses all changes for the given changeset into the previous
changesets if it exists.
"""
does_clear = self.has_clear(changeset_id)
changeset_data = self.pop_changeset(changeset_id)
if not self.is_empty():
# we only have to assign changeset data into the latest changeset if
# there is one.
if does_clear:
# if there was a clear and more changesets underneath then clear the latest
# changeset, and replace with a new clear changeset
self.latest = {}
self._clears_at.add(self.latest_id)
self.record_changeset()
self.latest = changeset_data
else:
# otherwise, merge in all the current data
self.latest = merge(
self.latest,
changeset_data,
)
return changeset_data | [
"def",
"commit_changeset",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"Dict",
"[",
"bytes",
",",
"Union",
"[",
"bytes",
",",
"DeletedEntry",
"]",
"]",
":",
"does_clear",
"=",
"self",
".",
"has_clear",
"(",
"changeset_id",
")",... | Collapses all changes for the given changeset into the previous
changesets if it exists. | [
"Collapses",
"all",
"changes",
"for",
"the",
"given",
"changeset",
"into",
"the",
"previous",
"changesets",
"if",
"it",
"exists",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L168-L191 | train | 224,967 |
ethereum/py-evm | eth/db/journal.py | JournalDB._validate_changeset | def _validate_changeset(self, changeset_id: uuid.UUID) -> None:
"""
Checks to be sure the changeset is known by the journal
"""
if not self.journal.has_changeset(changeset_id):
raise ValidationError("Changeset not found in journal: {0}".format(
str(changeset_id)
)) | python | def _validate_changeset(self, changeset_id: uuid.UUID) -> None:
"""
Checks to be sure the changeset is known by the journal
"""
if not self.journal.has_changeset(changeset_id):
raise ValidationError("Changeset not found in journal: {0}".format(
str(changeset_id)
)) | [
"def",
"_validate_changeset",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"journal",
".",
"has_changeset",
"(",
"changeset_id",
")",
":",
"raise",
"ValidationError",
"(",
"\"Changeset not found ... | Checks to be sure the changeset is known by the journal | [
"Checks",
"to",
"be",
"sure",
"the",
"changeset",
"is",
"known",
"by",
"the",
"journal"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L354-L361 | train | 224,968 |
ethereum/py-evm | eth/db/journal.py | JournalDB.record | def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Starts a new recording and returns an id for the associated changeset
"""
return self.journal.record_changeset(custom_changeset_id) | python | def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Starts a new recording and returns an id for the associated changeset
"""
return self.journal.record_changeset(custom_changeset_id) | [
"def",
"record",
"(",
"self",
",",
"custom_changeset_id",
":",
"uuid",
".",
"UUID",
"=",
"None",
")",
"->",
"uuid",
".",
"UUID",
":",
"return",
"self",
".",
"journal",
".",
"record_changeset",
"(",
"custom_changeset_id",
")"
] | Starts a new recording and returns an id for the associated changeset | [
"Starts",
"a",
"new",
"recording",
"and",
"returns",
"an",
"id",
"for",
"the",
"associated",
"changeset"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L366-L370 | train | 224,969 |
ethereum/py-evm | eth/db/journal.py | JournalDB.discard | def discard(self, changeset_id: uuid.UUID) -> None:
"""
Throws away all journaled data starting at the given changeset
"""
self._validate_changeset(changeset_id)
self.journal.pop_changeset(changeset_id) | python | def discard(self, changeset_id: uuid.UUID) -> None:
"""
Throws away all journaled data starting at the given changeset
"""
self._validate_changeset(changeset_id)
self.journal.pop_changeset(changeset_id) | [
"def",
"discard",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"None",
":",
"self",
".",
"_validate_changeset",
"(",
"changeset_id",
")",
"self",
".",
"journal",
".",
"pop_changeset",
"(",
"changeset_id",
")"
] | Throws away all journaled data starting at the given changeset | [
"Throws",
"away",
"all",
"journaled",
"data",
"starting",
"at",
"the",
"given",
"changeset"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L372-L377 | train | 224,970 |
ethereum/py-evm | eth/db/journal.py | JournalDB.commit | def commit(self, changeset_id: uuid.UUID) -> None:
"""
Commits a given changeset. This merges the given changeset and all
subsequent changesets into the previous changeset giving precidence
to later changesets in case of any conflicting keys.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB().
"""
self._validate_changeset(changeset_id)
journal_data = self.journal.commit_changeset(changeset_id)
if self.journal.is_empty():
# Ensure the journal automatically restarts recording after
# it has been persisted to the underlying db
self.reset()
for key, value in journal_data.items():
try:
if value is DELETED_ENTRY:
del self.wrapped_db[key]
elif value is ERASE_CREATED_ENTRY:
pass
else:
self.wrapped_db[key] = cast(bytes, value)
except Exception:
self._reapply_changeset_to_journal(changeset_id, journal_data)
raise | python | def commit(self, changeset_id: uuid.UUID) -> None:
"""
Commits a given changeset. This merges the given changeset and all
subsequent changesets into the previous changeset giving precidence
to later changesets in case of any conflicting keys.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB().
"""
self._validate_changeset(changeset_id)
journal_data = self.journal.commit_changeset(changeset_id)
if self.journal.is_empty():
# Ensure the journal automatically restarts recording after
# it has been persisted to the underlying db
self.reset()
for key, value in journal_data.items():
try:
if value is DELETED_ENTRY:
del self.wrapped_db[key]
elif value is ERASE_CREATED_ENTRY:
pass
else:
self.wrapped_db[key] = cast(bytes, value)
except Exception:
self._reapply_changeset_to_journal(changeset_id, journal_data)
raise | [
"def",
"commit",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"None",
":",
"self",
".",
"_validate_changeset",
"(",
"changeset_id",
")",
"journal_data",
"=",
"self",
".",
"journal",
".",
"commit_changeset",
"(",
"changeset_id",
")",... | Commits a given changeset. This merges the given changeset and all
subsequent changesets into the previous changeset giving precidence
to later changesets in case of any conflicting keys.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB(). | [
"Commits",
"a",
"given",
"changeset",
".",
"This",
"merges",
"the",
"given",
"changeset",
"and",
"all",
"subsequent",
"changesets",
"into",
"the",
"previous",
"changeset",
"giving",
"precidence",
"to",
"later",
"changesets",
"in",
"case",
"of",
"any",
"conflicti... | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L379-L408 | train | 224,971 |
ethereum/py-evm | eth/_utils/bn128.py | FQP_point_to_FQ2_point | def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]:
"""
Transform FQP to FQ2 for type hinting.
"""
return (
FQ2(pt[0].coeffs),
FQ2(pt[1].coeffs),
FQ2(pt[2].coeffs),
) | python | def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]:
"""
Transform FQP to FQ2 for type hinting.
"""
return (
FQ2(pt[0].coeffs),
FQ2(pt[1].coeffs),
FQ2(pt[2].coeffs),
) | [
"def",
"FQP_point_to_FQ2_point",
"(",
"pt",
":",
"Tuple",
"[",
"FQP",
",",
"FQP",
",",
"FQP",
"]",
")",
"->",
"Tuple",
"[",
"FQ2",
",",
"FQ2",
",",
"FQ2",
"]",
":",
"return",
"(",
"FQ2",
"(",
"pt",
"[",
"0",
"]",
".",
"coeffs",
")",
",",
"FQ2",... | Transform FQP to FQ2 for type hinting. | [
"Transform",
"FQP",
"to",
"FQ2",
"for",
"type",
"hinting",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/bn128.py#L34-L42 | train | 224,972 |
ethereum/py-evm | eth/vm/opcode.py | Opcode.as_opcode | def as_opcode(cls: Type[T],
logic_fn: Callable[..., Any],
mnemonic: str,
gas_cost: int) -> Type[T]:
"""
Class factory method for turning vanilla functions into Opcode classes.
"""
if gas_cost:
@functools.wraps(logic_fn)
def wrapped_logic_fn(computation: 'BaseComputation') -> Any:
"""
Wrapper functionf or the logic function which consumes the base
opcode gas cost prior to execution.
"""
computation.consume_gas(
gas_cost,
mnemonic,
)
return logic_fn(computation)
else:
wrapped_logic_fn = logic_fn
props = {
'__call__': staticmethod(wrapped_logic_fn),
'mnemonic': mnemonic,
'gas_cost': gas_cost,
}
opcode_cls = type("opcode:{0}".format(mnemonic), (cls,), props)
return opcode_cls() | python | def as_opcode(cls: Type[T],
logic_fn: Callable[..., Any],
mnemonic: str,
gas_cost: int) -> Type[T]:
"""
Class factory method for turning vanilla functions into Opcode classes.
"""
if gas_cost:
@functools.wraps(logic_fn)
def wrapped_logic_fn(computation: 'BaseComputation') -> Any:
"""
Wrapper functionf or the logic function which consumes the base
opcode gas cost prior to execution.
"""
computation.consume_gas(
gas_cost,
mnemonic,
)
return logic_fn(computation)
else:
wrapped_logic_fn = logic_fn
props = {
'__call__': staticmethod(wrapped_logic_fn),
'mnemonic': mnemonic,
'gas_cost': gas_cost,
}
opcode_cls = type("opcode:{0}".format(mnemonic), (cls,), props)
return opcode_cls() | [
"def",
"as_opcode",
"(",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"logic_fn",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
",",
"mnemonic",
":",
"str",
",",
"gas_cost",
":",
"int",
")",
"->",
"Type",
"[",
"T",
"]",
":",
"if",
"gas_cost",
":",
"... | Class factory method for turning vanilla functions into Opcode classes. | [
"Class",
"factory",
"method",
"for",
"turning",
"vanilla",
"functions",
"into",
"Opcode",
"classes",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/opcode.py#L52-L80 | train | 224,973 |
ethereum/py-evm | eth/db/account.py | AccountDB._wipe_storage | def _wipe_storage(self, address: Address) -> None:
"""
Wipe out the storage, without explicitly handling the storage root update
"""
account_store = self._get_address_store(address)
self._dirty_accounts.add(address)
account_store.delete() | python | def _wipe_storage(self, address: Address) -> None:
"""
Wipe out the storage, without explicitly handling the storage root update
"""
account_store = self._get_address_store(address)
self._dirty_accounts.add(address)
account_store.delete() | [
"def",
"_wipe_storage",
"(",
"self",
",",
"address",
":",
"Address",
")",
"->",
"None",
":",
"account_store",
"=",
"self",
".",
"_get_address_store",
"(",
"address",
")",
"self",
".",
"_dirty_accounts",
".",
"add",
"(",
"address",
")",
"account_store",
".",
... | Wipe out the storage, without explicitly handling the storage root update | [
"Wipe",
"out",
"the",
"storage",
"without",
"explicitly",
"handling",
"the",
"storage",
"root",
"update"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/account.py#L287-L293 | train | 224,974 |
ethereum/py-evm | eth/tools/fixtures/fillers/common.py | setup_main_filler | def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]:
"""
Kick off the filler generation process by creating the general filler scaffold with
a test name and general information about the testing environment.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+
"""
return setup_filler(name, merge(DEFAULT_MAIN_ENVIRONMENT, environment or {})) | python | def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]:
"""
Kick off the filler generation process by creating the general filler scaffold with
a test name and general information about the testing environment.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+
"""
return setup_filler(name, merge(DEFAULT_MAIN_ENVIRONMENT, environment or {})) | [
"def",
"setup_main_filler",
"(",
"name",
":",
"str",
",",
"environment",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"setup_filler",
"(",
"name"... | Kick off the filler generation process by creating the general filler scaffold with
a test name and general information about the testing environment.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+ | [
"Kick",
"off",
"the",
"filler",
"generation",
"process",
"by",
"creating",
"the",
"general",
"filler",
"scaffold",
"with",
"a",
"test",
"name",
"and",
"general",
"information",
"about",
"the",
"testing",
"environment",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L114-L138 | train | 224,975 |
ethereum/py-evm | eth/tools/fixtures/fillers/common.py | pre_state | def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None:
"""
Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>})
"""
@wraps(pre_state)
def _pre_state(filler: Dict[str, Any]) -> Dict[str, Any]:
test_name = get_test_name(filler)
old_pre_state = filler[test_name].get("pre_state", {})
pre_state = normalize_state(raw_state)
defaults = {address: {
"balance": 0,
"nonce": 0,
"code": b"",
"storage": {},
} for address in pre_state}
new_pre_state = deep_merge(defaults, old_pre_state, pre_state)
return assoc_in(filler, [test_name, "pre"], new_pre_state) | python | def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None:
"""
Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>})
"""
@wraps(pre_state)
def _pre_state(filler: Dict[str, Any]) -> Dict[str, Any]:
test_name = get_test_name(filler)
old_pre_state = filler[test_name].get("pre_state", {})
pre_state = normalize_state(raw_state)
defaults = {address: {
"balance": 0,
"nonce": 0,
"code": b"",
"storage": {},
} for address in pre_state}
new_pre_state = deep_merge(defaults, old_pre_state, pre_state)
return assoc_in(filler, [test_name, "pre"], new_pre_state) | [
"def",
"pre_state",
"(",
"*",
"raw_state",
":",
"GeneralState",
",",
"filler",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"@",
"wraps",
"(",
"pre_state",
")",
"def",
"_pre_state",
"(",
"filler",
":",
"Dict",
"[",
"str",
",",
... | Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>}) | [
"Specify",
"the",
"state",
"prior",
"to",
"the",
"test",
"execution",
".",
"Multiple",
"invocations",
"don",
"t",
"override",
"the",
"state",
"but",
"extend",
"it",
"instead",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L141-L185 | train | 224,976 |
ethereum/py-evm | eth/tools/fixtures/fillers/common.py | expect | def expect(post_state: Dict[str, Any]=None,
networks: Any=None,
transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]:
"""
Specify the expected result for the test.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``).
"""
return partial(_expect, post_state, networks, transaction) | python | def expect(post_state: Dict[str, Any]=None,
networks: Any=None,
transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]:
"""
Specify the expected result for the test.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``).
"""
return partial(_expect, post_state, networks, transaction) | [
"def",
"expect",
"(",
"post_state",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"networks",
":",
"Any",
"=",
"None",
",",
"transaction",
":",
"TransactionDict",
"=",
"None",
")",
"->",
"Callable",
"[",
"...",
",",
"Dict",
"[",
"str",
... | Specify the expected result for the test.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``). | [
"Specify",
"the",
"expected",
"result",
"for",
"the",
"test",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L245-L289 | train | 224,977 |
ethereum/py-evm | eth/vm/logic/context.py | calldataload | def calldataload(computation: BaseComputation) -> None:
"""
Load call data into memory.
"""
start_position = computation.stack_pop(type_hint=constants.UINT256)
value = computation.msg.data_as_bytes[start_position:start_position + 32]
padded_value = value.ljust(32, b'\x00')
normalized_value = padded_value.lstrip(b'\x00')
computation.stack_push(normalized_value) | python | def calldataload(computation: BaseComputation) -> None:
"""
Load call data into memory.
"""
start_position = computation.stack_pop(type_hint=constants.UINT256)
value = computation.msg.data_as_bytes[start_position:start_position + 32]
padded_value = value.ljust(32, b'\x00')
normalized_value = padded_value.lstrip(b'\x00')
computation.stack_push(normalized_value) | [
"def",
"calldataload",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"start_position",
"=",
"computation",
".",
"stack_pop",
"(",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"value",
"=",
"computation",
".",
"msg",
".",
"data_as_b... | Load call data into memory. | [
"Load",
"call",
"data",
"into",
"memory",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/context.py#L39-L49 | train | 224,978 |
ethereum/py-evm | eth/_utils/numeric.py | clamp | def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
"""
Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``.
"""
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclusive_upper_bound:
return inclusive_upper_bound
else:
return value | python | def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
"""
Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``.
"""
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclusive_upper_bound:
return inclusive_upper_bound
else:
return value | [
"def",
"clamp",
"(",
"inclusive_lower_bound",
":",
"int",
",",
"inclusive_upper_bound",
":",
"int",
",",
"value",
":",
"int",
")",
"->",
"int",
":",
"if",
"value",
"<=",
"inclusive_lower_bound",
":",
"return",
"inclusive_lower_bound",
"elif",
"value",
">=",
"i... | Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``. | [
"Bound",
"the",
"given",
"value",
"between",
"inclusive_lower_bound",
"and",
"inclusive_upper_bound",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/numeric.py#L90-L102 | train | 224,979 |
ethereum/py-evm | eth/_utils/numeric.py | integer_squareroot | def integer_squareroot(value: int) -> int:
"""
Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer.
"""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(
"Value must be an integer: Got: {0}".format(
type(value),
)
)
if value < 0:
raise ValueError(
"Value cannot be negative: Got: {0}".format(
value,
)
)
with decimal.localcontext() as ctx:
ctx.prec = 128
return int(decimal.Decimal(value).sqrt()) | python | def integer_squareroot(value: int) -> int:
"""
Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer.
"""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(
"Value must be an integer: Got: {0}".format(
type(value),
)
)
if value < 0:
raise ValueError(
"Value cannot be negative: Got: {0}".format(
value,
)
)
with decimal.localcontext() as ctx:
ctx.prec = 128
return int(decimal.Decimal(value).sqrt()) | [
"def",
"integer_squareroot",
"(",
"value",
":",
"int",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
"or",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"ValueError",
"(",
"\"Value must be an integer: Got: {0}... | Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer. | [
"Return",
"the",
"integer",
"square",
"root",
"of",
"value",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/numeric.py#L105-L128 | train | 224,980 |
ethereum/py-evm | eth/db/atomic.py | AtomicDBWriteBatch._commit_unless_raises | def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']:
"""
Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB.
"""
readable_write_batch = cls(write_target_db) # type: AtomicDBWriteBatch
try:
yield readable_write_batch
except Exception:
cls.logger.exception(
"Unexpected error in atomic db write, dropped partial writes: %r",
readable_write_batch._diff(),
)
raise
else:
readable_write_batch._commit()
finally:
# force a shutdown of this batch, to prevent out-of-context usage
readable_write_batch._track_diff = None
readable_write_batch._write_target_db = None | python | def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']:
"""
Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB.
"""
readable_write_batch = cls(write_target_db) # type: AtomicDBWriteBatch
try:
yield readable_write_batch
except Exception:
cls.logger.exception(
"Unexpected error in atomic db write, dropped partial writes: %r",
readable_write_batch._diff(),
)
raise
else:
readable_write_batch._commit()
finally:
# force a shutdown of this batch, to prevent out-of-context usage
readable_write_batch._track_diff = None
readable_write_batch._write_target_db = None | [
"def",
"_commit_unless_raises",
"(",
"cls",
",",
"write_target_db",
":",
"BaseDB",
")",
"->",
"Iterator",
"[",
"'AtomicDBWriteBatch'",
"]",
":",
"readable_write_batch",
"=",
"cls",
"(",
"write_target_db",
")",
"# type: AtomicDBWriteBatch",
"try",
":",
"yield",
"read... | Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB. | [
"Commit",
"all",
"writes",
"inside",
"the",
"context",
"unless",
"an",
"exception",
"was",
"raised",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/atomic.py#L116-L137 | train | 224,981 |
ethereum/py-evm | eth/vm/logic/comparison.py | slt | def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
left, right = map(
unsigned_to_signed,
computation.stack_pop(num_items=2, type_hint=constants.UINT256),
)
if left < right:
result = 1
else:
result = 0
computation.stack_push(signed_to_unsigned(result)) | python | def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
left, right = map(
unsigned_to_signed,
computation.stack_pop(num_items=2, type_hint=constants.UINT256),
)
if left < right:
result = 1
else:
result = 0
computation.stack_push(signed_to_unsigned(result)) | [
"def",
"slt",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"left",
",",
"right",
"=",
"map",
"(",
"unsigned_to_signed",
",",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT2... | Signed Lesser Comparison | [
"Signed",
"Lesser",
"Comparison"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/comparison.py#L39-L53 | train | 224,982 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | build | def build(obj: Any, *applicators: Callable[..., Any]) -> Any:
"""
Run the provided object through the series of applicator functions.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance.
"""
if isinstance(obj, BaseChain):
return pipe(obj, copy(), *applicators)
else:
return pipe(obj, *applicators) | python | def build(obj: Any, *applicators: Callable[..., Any]) -> Any:
"""
Run the provided object through the series of applicator functions.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance.
"""
if isinstance(obj, BaseChain):
return pipe(obj, copy(), *applicators)
else:
return pipe(obj, *applicators) | [
"def",
"build",
"(",
"obj",
":",
"Any",
",",
"*",
"applicators",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BaseChain",
")",
":",
"return",
"pipe",
"(",
"obj",
",",
"copy",
"(",
")",... | Run the provided object through the series of applicator functions.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance. | [
"Run",
"the",
"provided",
"object",
"through",
"the",
"series",
"of",
"applicator",
"functions",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L78-L89 | train | 224,983 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | name | def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Assign the given name to the chain class.
"""
return chain_class.configure(__name__=class_name) | python | def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Assign the given name to the chain class.
"""
return chain_class.configure(__name__=class_name) | [
"def",
"name",
"(",
"class_name",
":",
"str",
",",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"return",
"chain_class",
".",
"configure",
"(",
"__name__",
"=",
"class_name",
")"
] | Assign the given name to the chain class. | [
"Assign",
"the",
"given",
"name",
"to",
"the",
"chain",
"class",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L96-L100 | train | 224,984 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | chain_id | def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``chain_id`` for the chain class.
"""
return chain_class.configure(chain_id=chain_id) | python | def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``chain_id`` for the chain class.
"""
return chain_class.configure(chain_id=chain_id) | [
"def",
"chain_id",
"(",
"chain_id",
":",
"int",
",",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"return",
"chain_class",
".",
"configure",
"(",
"chain_id",
"=",
"chain_id",
")"
] | Set the ``chain_id`` for the chain class. | [
"Set",
"the",
"chain_id",
"for",
"the",
"chain",
"class",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L104-L108 | train | 224,985 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | fork_at | def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at`
"""
if chain_class.vm_configuration is not None:
base_configuration = chain_class.vm_configuration
else:
base_configuration = tuple()
vm_configuration = base_configuration + ((at_block, vm_class),)
validate_vm_configuration(vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | python | def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at`
"""
if chain_class.vm_configuration is not None:
base_configuration = chain_class.vm_configuration
else:
base_configuration = tuple()
vm_configuration = base_configuration + ((at_block, vm_class),)
validate_vm_configuration(vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | [
"def",
"fork_at",
"(",
"vm_class",
":",
"Type",
"[",
"BaseVM",
"]",
",",
"at_block",
":",
"int",
",",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"if",
"chain_class",
".",
"vm_configuration",
"is",
... | Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at` | [
"Adds",
"the",
"vm_class",
"to",
"the",
"chain",
"s",
"vm_configuration",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L112-L148 | train | 224,986 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | enable_pow_mining | def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
vm_configuration = _mix_in_pow_mining(chain_class.vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | python | def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
vm_configuration = _mix_in_pow_mining(chain_class.vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | [
"def",
"enable_pow_mining",
"(",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"if",
"not",
"chain_class",
".",
"vm_configuration",
":",
"raise",
"ValidationError",
"(",
"\"Chain class has no vm_configuration\"",
... | Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms. | [
"Inject",
"on",
"demand",
"generation",
"of",
"the",
"proof",
"of",
"work",
"mining",
"seal",
"on",
"newly",
"mined",
"blocks",
"into",
"each",
"of",
"the",
"chain",
"s",
"vms",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L269-L278 | train | 224,987 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | disable_pow_check | def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Disable the proof of work validation check for each of the chain's vms.
This allows for block mining without generation of the proof of work seal.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
if issubclass(chain_class, NoChainSealValidationMixin):
# Seal validation already disabled, hence nothing to change
chain_class_without_seal_validation = chain_class
else:
chain_class_without_seal_validation = type(
chain_class.__name__,
(chain_class, NoChainSealValidationMixin),
{},
)
return chain_class_without_seal_validation.configure( # type: ignore
vm_configuration=_mix_in_disable_seal_validation(
chain_class_without_seal_validation.vm_configuration # type: ignore
),
) | python | def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Disable the proof of work validation check for each of the chain's vms.
This allows for block mining without generation of the proof of work seal.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
if issubclass(chain_class, NoChainSealValidationMixin):
# Seal validation already disabled, hence nothing to change
chain_class_without_seal_validation = chain_class
else:
chain_class_without_seal_validation = type(
chain_class.__name__,
(chain_class, NoChainSealValidationMixin),
{},
)
return chain_class_without_seal_validation.configure( # type: ignore
vm_configuration=_mix_in_disable_seal_validation(
chain_class_without_seal_validation.vm_configuration # type: ignore
),
) | [
"def",
"disable_pow_check",
"(",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"if",
"not",
"chain_class",
".",
"vm_configuration",
":",
"raise",
"ValidationError",
"(",
"\"Chain class has no vm_configuration\"",
... | Disable the proof of work validation check for each of the chain's vms.
This allows for block mining without generation of the proof of work seal.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled. | [
"Disable",
"the",
"proof",
"of",
"work",
"validation",
"check",
"for",
"each",
"of",
"the",
"chain",
"s",
"vms",
".",
"This",
"allows",
"for",
"block",
"mining",
"without",
"generation",
"of",
"the",
"proof",
"of",
"work",
"seal",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L309-L335 | train | 224,988 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | genesis | def genesis(chain_class: BaseChain,
db: BaseAtomicDB=None,
params: Dict[str, HeaderParams]=None,
state: GeneralState=None) -> BaseChain:
"""
Initialize the given chain class with the given genesis header parameters
and chain state.
"""
if state is None:
genesis_state = {} # type: AccountState
else:
genesis_state = _fill_and_normalize_state(state)
genesis_params_defaults = _get_default_genesis_params(genesis_state)
if params is None:
genesis_params = genesis_params_defaults
else:
genesis_params = merge(genesis_params_defaults, params)
if db is None:
base_db = AtomicDB() # type: BaseAtomicDB
else:
base_db = db
return chain_class.from_genesis(base_db, genesis_params, genesis_state) | python | def genesis(chain_class: BaseChain,
db: BaseAtomicDB=None,
params: Dict[str, HeaderParams]=None,
state: GeneralState=None) -> BaseChain:
"""
Initialize the given chain class with the given genesis header parameters
and chain state.
"""
if state is None:
genesis_state = {} # type: AccountState
else:
genesis_state = _fill_and_normalize_state(state)
genesis_params_defaults = _get_default_genesis_params(genesis_state)
if params is None:
genesis_params = genesis_params_defaults
else:
genesis_params = merge(genesis_params_defaults, params)
if db is None:
base_db = AtomicDB() # type: BaseAtomicDB
else:
base_db = db
return chain_class.from_genesis(base_db, genesis_params, genesis_state) | [
"def",
"genesis",
"(",
"chain_class",
":",
"BaseChain",
",",
"db",
":",
"BaseAtomicDB",
"=",
"None",
",",
"params",
":",
"Dict",
"[",
"str",
",",
"HeaderParams",
"]",
"=",
"None",
",",
"state",
":",
"GeneralState",
"=",
"None",
")",
"->",
"BaseChain",
... | Initialize the given chain class with the given genesis header parameters
and chain state. | [
"Initialize",
"the",
"given",
"chain",
"class",
"with",
"the",
"given",
"genesis",
"header",
"parameters",
"and",
"chain",
"state",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L354-L379 | train | 224,989 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | mine_block | def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain:
"""
Mine a new block on the chain. Header parameters for the new block can be
overridden using keyword arguments.
"""
if not isinstance(chain, MiningChain):
raise ValidationError('`mine_block` may only be used on MiningChain instances')
chain.mine_block(**kwargs)
return chain | python | def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain:
"""
Mine a new block on the chain. Header parameters for the new block can be
overridden using keyword arguments.
"""
if not isinstance(chain, MiningChain):
raise ValidationError('`mine_block` may only be used on MiningChain instances')
chain.mine_block(**kwargs)
return chain | [
"def",
"mine_block",
"(",
"chain",
":",
"MiningChain",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"MiningChain",
":",
"if",
"not",
"isinstance",
"(",
"chain",
",",
"MiningChain",
")",
":",
"raise",
"ValidationError",
"(",
"'`mine_block` may only be used o... | Mine a new block on the chain. Header parameters for the new block can be
overridden using keyword arguments. | [
"Mine",
"a",
"new",
"block",
"on",
"the",
"chain",
".",
"Header",
"parameters",
"for",
"the",
"new",
"block",
"can",
"be",
"overridden",
"using",
"keyword",
"arguments",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L386-L395 | train | 224,990 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | import_block | def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain:
"""
Import the provided ``block`` into the chain.
"""
chain.import_block(block)
return chain | python | def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain:
"""
Import the provided ``block`` into the chain.
"""
chain.import_block(block)
return chain | [
"def",
"import_block",
"(",
"block",
":",
"BaseBlock",
",",
"chain",
":",
"BaseChain",
")",
"->",
"BaseChain",
":",
"chain",
".",
"import_block",
"(",
"block",
")",
"return",
"chain"
] | Import the provided ``block`` into the chain. | [
"Import",
"the",
"provided",
"block",
"into",
"the",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L411-L416 | train | 224,991 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | copy | def copy(chain: MiningChain) -> MiningChain:
"""
Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain.
"""
if not isinstance(chain, MiningChain):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
base_db = chain.chaindb.db
if not isinstance(base_db, AtomicDB):
raise ValidationError("Unsupported database type: {0}".format(type(base_db)))
if isinstance(base_db.wrapped_db, MemoryDB):
db = AtomicDB(MemoryDB(base_db.wrapped_db.kv_store.copy()))
else:
raise ValidationError("Unsupported wrapped database: {0}".format(type(base_db.wrapped_db)))
chain_copy = type(chain)(db, chain.header)
return chain_copy | python | def copy(chain: MiningChain) -> MiningChain:
"""
Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain.
"""
if not isinstance(chain, MiningChain):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
base_db = chain.chaindb.db
if not isinstance(base_db, AtomicDB):
raise ValidationError("Unsupported database type: {0}".format(type(base_db)))
if isinstance(base_db.wrapped_db, MemoryDB):
db = AtomicDB(MemoryDB(base_db.wrapped_db.kv_store.copy()))
else:
raise ValidationError("Unsupported wrapped database: {0}".format(type(base_db.wrapped_db)))
chain_copy = type(chain)(db, chain.header)
return chain_copy | [
"def",
"copy",
"(",
"chain",
":",
"MiningChain",
")",
"->",
"MiningChain",
":",
"if",
"not",
"isinstance",
"(",
"chain",
",",
"MiningChain",
")",
":",
"raise",
"ValidationError",
"(",
"\"`at_block_number` may only be used with 'MiningChain\"",
")",
"base_db",
"=",
... | Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain. | [
"Make",
"a",
"copy",
"of",
"the",
"chain",
"at",
"the",
"given",
"state",
".",
"Actions",
"performed",
"on",
"the",
"resulting",
"chain",
"will",
"not",
"affect",
"the",
"original",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L433-L450 | train | 224,992 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | chain_split | def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501
"""
Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
)
"""
if not splits:
raise ValidationError("Cannot use `chain_split` without providing at least one split")
@functools.wraps(chain_split)
@to_tuple
def _chain_split(chain: BaseChain) -> Iterable[BaseChain]:
for split_fns in splits:
result = build(
chain,
*split_fns,
)
yield result
return _chain_split | python | def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501
"""
Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
)
"""
if not splits:
raise ValidationError("Cannot use `chain_split` without providing at least one split")
@functools.wraps(chain_split)
@to_tuple
def _chain_split(chain: BaseChain) -> Iterable[BaseChain]:
for split_fns in splits:
result = build(
chain,
*split_fns,
)
yield result
return _chain_split | [
"def",
"chain_split",
"(",
"*",
"splits",
":",
"Iterable",
"[",
"Callable",
"[",
"...",
",",
"Any",
"]",
"]",
")",
"->",
"Callable",
"[",
"[",
"BaseChain",
"]",
",",
"Iterable",
"[",
"BaseChain",
"]",
"]",
":",
"# noqa: E501",
"if",
"not",
"splits",
... | Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
) | [
"Construct",
"and",
"execute",
"multiple",
"concurrent",
"forks",
"of",
"the",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L453-L486 | train | 224,993 |
ethereum/py-evm | eth/tools/builder/chain/builders.py | at_block_number | def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:
"""
Rewind the chain back to the given block number. Calls to things like
``get_canonical_head`` will still return the canonical head of the chain,
however, you can use ``mine_block`` to mine fork chains.
"""
if not isinstance(chain, MiningChain):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
at_block = chain.get_canonical_block_by_number(block_number)
db = chain.chaindb.db
chain_at_block = type(chain)(db, chain.create_header_from_parent(at_block.header))
return chain_at_block | python | def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:
"""
Rewind the chain back to the given block number. Calls to things like
``get_canonical_head`` will still return the canonical head of the chain,
however, you can use ``mine_block`` to mine fork chains.
"""
if not isinstance(chain, MiningChain):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
at_block = chain.get_canonical_block_by_number(block_number)
db = chain.chaindb.db
chain_at_block = type(chain)(db, chain.create_header_from_parent(at_block.header))
return chain_at_block | [
"def",
"at_block_number",
"(",
"block_number",
":",
"BlockNumber",
",",
"chain",
":",
"MiningChain",
")",
"->",
"MiningChain",
":",
"if",
"not",
"isinstance",
"(",
"chain",
",",
"MiningChain",
")",
":",
"raise",
"ValidationError",
"(",
"\"`at_block_number` may onl... | Rewind the chain back to the given block number. Calls to things like
``get_canonical_head`` will still return the canonical head of the chain,
however, you can use ``mine_block`` to mine fork chains. | [
"Rewind",
"the",
"chain",
"back",
"to",
"the",
"given",
"block",
"number",
".",
"Calls",
"to",
"things",
"like",
"get_canonical_head",
"will",
"still",
"return",
"the",
"canonical",
"head",
"of",
"the",
"chain",
"however",
"you",
"can",
"use",
"mine_block",
... | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L490-L502 | train | 224,994 |
ethereum/py-evm | eth/tools/fixtures/loading.py | load_json_fixture | def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | python | def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | [
"def",
"load_json_fixture",
"(",
"fixture_path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"with",
"open",
"(",
"fixture_path",
")",
"as",
"fixture_file",
":",
"file_fixtures",
"=",
"json",
".",
"load",
"(",
"fixture_file",
")",
"r... | Loads a fixture file, caching the most recent files it loaded. | [
"Loads",
"a",
"fixture",
"file",
"caching",
"the",
"most",
"recent",
"files",
"it",
"loaded",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/loading.py#L54-L60 | train | 224,995 |
ethereum/py-evm | eth/tools/fixtures/loading.py | load_fixture | def load_fixture(fixture_path: str,
fixture_key: str,
normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]:
"""
Loads a specific fixture from a fixture file, optionally passing it through
a normalization function.
"""
file_fixtures = load_json_fixture(fixture_path)
fixture = normalize_fn(file_fixtures[fixture_key])
return fixture | python | def load_fixture(fixture_path: str,
fixture_key: str,
normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]:
"""
Loads a specific fixture from a fixture file, optionally passing it through
a normalization function.
"""
file_fixtures = load_json_fixture(fixture_path)
fixture = normalize_fn(file_fixtures[fixture_key])
return fixture | [
"def",
"load_fixture",
"(",
"fixture_path",
":",
"str",
",",
"fixture_key",
":",
"str",
",",
"normalize_fn",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
"=",
"identity",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"file_fixtures",
"=",
"load... | Loads a specific fixture from a fixture file, optionally passing it through
a normalization function. | [
"Loads",
"a",
"specific",
"fixture",
"from",
"a",
"fixture",
"file",
"optionally",
"passing",
"it",
"through",
"a",
"normalization",
"function",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/loading.py#L63-L72 | train | 224,996 |
ethereum/py-evm | eth/_utils/version.py | construct_evm_runtime_identifier | def construct_evm_runtime_identifier() -> str:
"""
Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5'
"""
return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format(
__version__,
platform=sys.platform,
v=sys.version_info,
# mypy Doesn't recognize the `sys` module as having an `implementation` attribute.
imp=sys.implementation,
) | python | def construct_evm_runtime_identifier() -> str:
"""
Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5'
"""
return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format(
__version__,
platform=sys.platform,
v=sys.version_info,
# mypy Doesn't recognize the `sys` module as having an `implementation` attribute.
imp=sys.implementation,
) | [
"def",
"construct_evm_runtime_identifier",
"(",
")",
"->",
"str",
":",
"return",
"\"Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}\"",
".",
"format",
"(",
"__version__",
",",
"platform",
"=",
"sys",
".",
"platform",
",",
"v",
"=",
"sys",
".",
"version_i... | Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5' | [
"Constructs",
"the",
"EVM",
"runtime",
"identifier",
"string"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/version.py#L6-L18 | train | 224,997 |
ethereum/py-evm | eth/estimators/gas.py | binary_gas_search | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete
"""
if not hasattr(transaction, 'sender'):
raise TypeError(
"Transaction is missing attribute sender.",
"If sending an unsigned transaction, use SpoofTransaction and provide the",
"sender using the 'from' parameter")
minimum_transaction = SpoofTransaction(
transaction,
gas=transaction.intrinsic_gas,
gas_price=0,
)
if _get_computation_error(state, minimum_transaction) is None:
return transaction.intrinsic_gas
maximum_transaction = SpoofTransaction(
transaction,
gas=state.gas_limit,
gas_price=0,
)
error = _get_computation_error(state, maximum_transaction)
if error is not None:
raise error
minimum_viable = state.gas_limit
maximum_out_of_gas = transaction.intrinsic_gas
while minimum_viable - maximum_out_of_gas > tolerance:
midpoint = (minimum_viable + maximum_out_of_gas) // 2
test_transaction = SpoofTransaction(transaction, gas=midpoint)
if _get_computation_error(state, test_transaction) is None:
minimum_viable = midpoint
else:
maximum_out_of_gas = midpoint
return minimum_viable | python | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete
"""
if not hasattr(transaction, 'sender'):
raise TypeError(
"Transaction is missing attribute sender.",
"If sending an unsigned transaction, use SpoofTransaction and provide the",
"sender using the 'from' parameter")
minimum_transaction = SpoofTransaction(
transaction,
gas=transaction.intrinsic_gas,
gas_price=0,
)
if _get_computation_error(state, minimum_transaction) is None:
return transaction.intrinsic_gas
maximum_transaction = SpoofTransaction(
transaction,
gas=state.gas_limit,
gas_price=0,
)
error = _get_computation_error(state, maximum_transaction)
if error is not None:
raise error
minimum_viable = state.gas_limit
maximum_out_of_gas = transaction.intrinsic_gas
while minimum_viable - maximum_out_of_gas > tolerance:
midpoint = (minimum_viable + maximum_out_of_gas) // 2
test_transaction = SpoofTransaction(transaction, gas=midpoint)
if _get_computation_error(state, test_transaction) is None:
minimum_viable = midpoint
else:
maximum_out_of_gas = midpoint
return minimum_viable | [
"def",
"binary_gas_search",
"(",
"state",
":",
"BaseState",
",",
"transaction",
":",
"BaseTransaction",
",",
"tolerance",
":",
"int",
"=",
"1",
")",
"->",
"int",
":",
"if",
"not",
"hasattr",
"(",
"transaction",
",",
"'sender'",
")",
":",
"raise",
"TypeErro... | Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete | [
"Run",
"the",
"transaction",
"with",
"various",
"gas",
"limits",
"progressively",
"approaching",
"the",
"minimum",
"needed",
"to",
"succeed",
"without",
"an",
"OutOfGas",
"exception",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/estimators/gas.py#L28-L78 | train | 224,998 |
ethereum/py-evm | eth/db/storage.py | StorageLookup.commit_to | def commit_to(self, db: BaseDB) -> None:
"""
Trying to commit changes when nothing has been written will raise a
ValidationError
"""
self.logger.debug2('persist storage root to data store')
if self._trie_nodes_batch is None:
raise ValidationError(
"It is invalid to commit an account's storage if it has no pending changes. "
"Always check storage_lookup.has_changed_root before attempting to commit."
)
self._trie_nodes_batch.commit_to(db, apply_deletes=False)
self._clear_changed_root() | python | def commit_to(self, db: BaseDB) -> None:
"""
Trying to commit changes when nothing has been written will raise a
ValidationError
"""
self.logger.debug2('persist storage root to data store')
if self._trie_nodes_batch is None:
raise ValidationError(
"It is invalid to commit an account's storage if it has no pending changes. "
"Always check storage_lookup.has_changed_root before attempting to commit."
)
self._trie_nodes_batch.commit_to(db, apply_deletes=False)
self._clear_changed_root() | [
"def",
"commit_to",
"(",
"self",
",",
"db",
":",
"BaseDB",
")",
"->",
"None",
":",
"self",
".",
"logger",
".",
"debug2",
"(",
"'persist storage root to data store'",
")",
"if",
"self",
".",
"_trie_nodes_batch",
"is",
"None",
":",
"raise",
"ValidationError",
... | Trying to commit changes when nothing has been written will raise a
ValidationError | [
"Trying",
"to",
"commit",
"changes",
"when",
"nothing",
"has",
"been",
"written",
"will",
"raise",
"a",
"ValidationError"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/storage.py#L131-L143 | train | 224,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.