idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
234,200 | def connection_made ( self , transport : asyncio . BaseTransport ) -> None : if self . _stream_reader is None : raise SMTPServerDisconnected ( "Client not connected" ) self . _stream_reader . _transport = transport # type: ignore self . _over_ssl = transport . get_extra_info ( "sslcontext" ) is not None self . _stream_writer = asyncio . StreamWriter ( transport , self , self . _stream_reader , self . _loop ) self . _client_connected_cb ( # type: ignore self . _stream_reader , self . _stream_writer ) | Modified connection_made that supports upgrading our transport in place using STARTTLS . | 137 | 17 |
234,201 | def upgrade_transport ( self , context : ssl . SSLContext , server_hostname : str = None , waiter : Awaitable = None , ) -> SSLProtocol : if self . _over_ssl : raise RuntimeError ( "Already using TLS." ) if self . _stream_reader is None or self . _stream_writer is None : raise SMTPServerDisconnected ( "Client not connected" ) transport = self . _stream_reader . _transport # type: ignore tls_protocol = SSLProtocol ( self . _loop , self , context , waiter , server_side = False , server_hostname = server_hostname , ) app_transport = tls_protocol . _app_transport # Use set_protocol if we can if hasattr ( transport , "set_protocol" ) : transport . set_protocol ( tls_protocol ) else : transport . _protocol = tls_protocol self . _stream_reader . _transport = app_transport # type: ignore self . _stream_writer . _transport = app_transport # type: ignore tls_protocol . connection_made ( transport ) self . _over_ssl = True # type: bool return tls_protocol | Upgrade our transport to TLS in place . | 276 | 8 |
234,202 | async def read_response ( self , timeout : NumType = None ) -> SMTPResponse : if self . _stream_reader is None : raise SMTPServerDisconnected ( "Client not connected" ) code = None response_lines = [ ] while True : async with self . _io_lock : line = await self . _readline ( timeout = timeout ) try : code = int ( line [ : 3 ] ) except ValueError : pass message = line [ 4 : ] . strip ( b" \t\r\n" ) . decode ( "utf-8" , "surrogateescape" ) response_lines . append ( message ) if line [ 3 : 4 ] != b"-" : break full_message = "\n" . join ( response_lines ) if code is None : raise SMTPResponseException ( SMTPStatus . invalid_response . value , "Malformed SMTP response: {}" . format ( full_message ) , ) return SMTPResponse ( code , full_message ) | Get a status reponse from the server . | 222 | 9 |
234,203 | async def write_and_drain ( self , data : bytes , timeout : NumType = None ) -> None : if self . _stream_writer is None : raise SMTPServerDisconnected ( "Client not connected" ) self . _stream_writer . write ( data ) async with self . _io_lock : await self . _drain_writer ( timeout ) | Format a command and send it to the server . | 80 | 10 |
234,204 | async def write_message_data ( self , data : bytes , timeout : NumType = None ) -> None : data = LINE_ENDINGS_REGEX . sub ( b"\r\n" , data ) data = PERIOD_REGEX . sub ( b".." , data ) if not data . endswith ( b"\r\n" ) : data += b"\r\n" data += b".\r\n" await self . write_and_drain ( data , timeout = timeout ) | Encode and write email message data . | 116 | 8 |
234,205 | async def execute_command ( self , * args : bytes , timeout : NumType = None ) -> SMTPResponse : command = b" " . join ( args ) + b"\r\n" await self . write_and_drain ( command , timeout = timeout ) response = await self . read_response ( timeout = timeout ) return response | Sends an SMTP command along with any args to the server and returns a response . | 77 | 18 |
234,206 | def last_ehlo_response ( self , response : SMTPResponse ) -> None : extensions , auth_methods = parse_esmtp_extensions ( response . message ) self . _last_ehlo_response = response self . esmtp_extensions = extensions self . server_auth_methods = auth_methods self . supports_esmtp = True | When setting the last EHLO response parse the message for supported extensions and auth methods . | 84 | 18 |
234,207 | async def helo ( self , hostname : str = None , timeout : DefaultNumType = _default ) -> SMTPResponse : if hostname is None : hostname = self . source_address async with self . _command_lock : response = await self . execute_command ( b"HELO" , hostname . encode ( "ascii" ) , timeout = timeout ) self . last_helo_response = response if response . code != SMTPStatus . completed : raise SMTPHeloError ( response . code , response . message ) return response | Send the SMTP HELO command . Hostname to send for this command defaults to the FQDN of the local host . | 124 | 26 |
234,208 | async def help ( self , timeout : DefaultNumType = _default ) -> str : await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"HELP" , timeout = timeout ) success_codes = ( SMTPStatus . system_status_ok , SMTPStatus . help_message , SMTPStatus . completed , ) if response . code not in success_codes : raise SMTPResponseException ( response . code , response . message ) return response . message | Send the SMTP HELP command which responds with help text . | 125 | 12 |
234,209 | async def noop ( self , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"NOOP" , timeout = timeout ) if response . code != SMTPStatus . completed : raise SMTPResponseException ( response . code , response . message ) return response | Send an SMTP NOOP command which does nothing . | 98 | 11 |
234,210 | async def vrfy ( self , address : str , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) parsed_address = parse_address ( address ) async with self . _command_lock : response = await self . execute_command ( b"VRFY" , parsed_address . encode ( "ascii" ) , timeout = timeout ) success_codes = ( SMTPStatus . completed , SMTPStatus . will_forward , SMTPStatus . cannot_vrfy , ) if response . code not in success_codes : raise SMTPResponseException ( response . code , response . message ) return response | Send an SMTP VRFY command which tests an address for validity . Not many servers support this command . | 154 | 21 |
234,211 | async def expn ( self , address : str , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) parsed_address = parse_address ( address ) async with self . _command_lock : response = await self . execute_command ( b"EXPN" , parsed_address . encode ( "ascii" ) , timeout = timeout ) if response . code != SMTPStatus . completed : raise SMTPResponseException ( response . code , response . message ) return response | Send an SMTP EXPN command which expands a mailing list . Not many servers support this command . | 125 | 20 |
234,212 | async def quit ( self , timeout : DefaultNumType = _default ) -> SMTPResponse : # Can't quit without HELO/EHLO await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"QUIT" , timeout = timeout ) if response . code != SMTPStatus . closing : raise SMTPResponseException ( response . code , response . message ) self . close ( ) return response | Send the SMTP QUIT command which closes the connection . Also closes the connection from our side after a response is received . | 113 | 25 |
234,213 | async def rcpt ( self , recipient : str , options : Iterable [ str ] = None , timeout : DefaultNumType = _default , ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) if options is None : options = [ ] options_bytes = [ option . encode ( "ascii" ) for option in options ] to = b"TO:" + quote_address ( recipient ) . encode ( "ascii" ) async with self . _command_lock : response = await self . execute_command ( b"RCPT" , to , * options_bytes , timeout = timeout ) success_codes = ( SMTPStatus . completed , SMTPStatus . will_forward ) if response . code not in success_codes : raise SMTPRecipientRefused ( response . code , response . message , recipient ) return response | Send an SMTP RCPT command which specifies a single recipient for the message . This command is sent once per recipient and must be preceded by MAIL . | 192 | 32 |
234,214 | async def data ( self , message : Union [ str , bytes ] , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) # As data accesses protocol directly, some handling is required self . _raise_error_if_disconnected ( ) if timeout is _default : timeout = self . timeout # type: ignore if isinstance ( message , str ) : message = message . encode ( "ascii" ) async with self . _command_lock : start_response = await self . execute_command ( b"DATA" , timeout = timeout ) if start_response . code != SMTPStatus . start_input : raise SMTPDataError ( start_response . code , start_response . message ) try : await self . protocol . write_message_data ( # type: ignore message , timeout = timeout ) response = await self . protocol . read_response ( # type: ignore timeout = timeout ) except SMTPServerDisconnected as exc : self . close ( ) raise exc if response . code != SMTPStatus . completed : raise SMTPDataError ( response . code , response . message ) return response | Send an SMTP DATA command followed by the message given . This method transfers the actual email content to the server . | 259 | 23 |
234,215 | async def ehlo ( self , hostname : str = None , timeout : DefaultNumType = _default ) -> SMTPResponse : if hostname is None : hostname = self . source_address async with self . _command_lock : response = await self . execute_command ( b"EHLO" , hostname . encode ( "ascii" ) , timeout = timeout ) self . last_ehlo_response = response if response . code != SMTPStatus . completed : raise SMTPHeloError ( response . code , response . message ) return response | Send the SMTP EHLO command . Hostname to send for this command defaults to the FQDN of the local host . | 124 | 27 |
234,216 | def _reset_server_state ( self ) -> None : self . last_helo_response = None self . _last_ehlo_response = None self . esmtp_extensions = { } self . supports_esmtp = False self . server_auth_methods = [ ] | Clear stored information about the server . | 65 | 7 |
234,217 | def supported_auth_methods ( self ) -> List [ str ] : return [ auth for auth in self . AUTH_METHODS if auth in self . server_auth_methods ] | Get all AUTH methods supported by the both server and by us . | 40 | 13 |
234,218 | async def login ( self , username : str , password : str , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) if not self . supports_extension ( "auth" ) : raise SMTPException ( "SMTP AUTH extension not supported by server." ) response = None # type: Optional[SMTPResponse] exception = None # type: Optional[SMTPAuthenticationError] for auth_name in self . supported_auth_methods : method_name = "auth_{}" . format ( auth_name . replace ( "-" , "" ) ) try : auth_method = getattr ( self , method_name ) except AttributeError : raise RuntimeError ( "Missing handler for auth method {}" . format ( auth_name ) ) try : response = await auth_method ( username , password , timeout = timeout ) except SMTPAuthenticationError as exc : exception = exc else : # No exception means we're good break if response is None : raise exception or SMTPException ( "No suitable authentication method found." ) return response | Tries to login with supported auth methods . | 248 | 9 |
234,219 | async def auth_crammd5 ( self , username : str , password : str , timeout : DefaultNumType = _default ) -> SMTPResponse : async with self . _command_lock : initial_response = await self . execute_command ( b"AUTH" , b"CRAM-MD5" , timeout = timeout ) if initial_response . code != SMTPStatus . auth_continue : raise SMTPAuthenticationError ( initial_response . code , initial_response . message ) password_bytes = password . encode ( "ascii" ) username_bytes = username . encode ( "ascii" ) response_bytes = initial_response . message . encode ( "ascii" ) verification_bytes = crammd5_verify ( username_bytes , password_bytes , response_bytes ) response = await self . execute_command ( verification_bytes ) if response . code != SMTPStatus . auth_successful : raise SMTPAuthenticationError ( response . code , response . message ) return response | CRAM - MD5 auth uses the password as a shared secret to MD5 the server s response . | 225 | 21 |
234,220 | async def auth_plain ( self , username : str , password : str , timeout : DefaultNumType = _default ) -> SMTPResponse : username_bytes = username . encode ( "ascii" ) password_bytes = password . encode ( "ascii" ) username_and_password = b"\0" + username_bytes + b"\0" + password_bytes encoded = base64 . b64encode ( username_and_password ) async with self . _command_lock : response = await self . execute_command ( b"AUTH" , b"PLAIN" , encoded , timeout = timeout ) if response . code != SMTPStatus . auth_successful : raise SMTPAuthenticationError ( response . code , response . message ) return response | PLAIN auth encodes the username and password in one Base64 encoded string . No verification message is required . | 170 | 22 |
234,221 | async def auth_login ( self , username : str , password : str , timeout : DefaultNumType = _default ) -> SMTPResponse : encoded_username = base64 . b64encode ( username . encode ( "ascii" ) ) encoded_password = base64 . b64encode ( password . encode ( "ascii" ) ) async with self . _command_lock : initial_response = await self . execute_command ( b"AUTH" , b"LOGIN" , encoded_username , timeout = timeout ) if initial_response . code != SMTPStatus . auth_continue : raise SMTPAuthenticationError ( initial_response . code , initial_response . message ) response = await self . execute_command ( encoded_password , timeout = timeout ) if response . code != SMTPStatus . auth_successful : raise SMTPAuthenticationError ( response . code , response . message ) return response | LOGIN auth sends the Base64 encoded username and password in sequence . | 204 | 14 |
234,222 | def parse_address ( address : str ) -> str : display_name , parsed_address = email . utils . parseaddr ( address ) return parsed_address or address | Parse an email address falling back to the raw string given . | 36 | 13 |
234,223 | def quote_address ( address : str ) -> str : display_name , parsed_address = email . utils . parseaddr ( address ) if parsed_address : quoted_address = "<{}>" . format ( parsed_address ) # parseaddr couldn't parse it, use it as is and hope for the best. else : quoted_address = "<{}>" . format ( address . strip ( ) ) return quoted_address | Quote a subset of the email addresses defined by RFC 821 . | 91 | 13 |
234,224 | def _extract_sender ( message : Message , resent_dates : List [ Union [ str , Header ] ] = None ) -> str : if resent_dates : sender_header = "Resent-Sender" from_header = "Resent-From" else : sender_header = "Sender" from_header = "From" # Prefer the sender field per RFC 2822:3.6.2. if sender_header in message : sender = message [ sender_header ] else : sender = message [ from_header ] return str ( sender ) if sender else "" | Extract the sender from the message object given . | 125 | 10 |
234,225 | def _extract_recipients ( message : Message , resent_dates : List [ Union [ str , Header ] ] = None ) -> List [ str ] : recipients = [ ] # type: List[str] if resent_dates : recipient_headers = ( "Resent-To" , "Resent-Cc" , "Resent-Bcc" ) else : recipient_headers = ( "To" , "Cc" , "Bcc" ) for header in recipient_headers : recipients . extend ( message . get_all ( header , [ ] ) ) # type: ignore parsed_recipients = [ str ( email . utils . formataddr ( address ) ) for address in email . utils . getaddresses ( recipients ) ] return parsed_recipients | Extract the recipients from the message object given . | 168 | 10 |
234,226 | async def execute_command ( self , * args : bytes , timeout : DefaultNumType = _default ) -> SMTPResponse : if timeout is _default : timeout = self . timeout # type: ignore self . _raise_error_if_disconnected ( ) try : response = await self . protocol . execute_command ( # type: ignore * args , timeout = timeout ) except SMTPServerDisconnected : # On disconnect, clean up the connection. self . close ( ) raise # If the server is unavailable, be nice and close the connection if response . code == SMTPStatus . domain_unavailable : self . close ( ) return response | Check that we re connected if we got a timeout value and then pass the command to the protocol . | 138 | 20 |
234,227 | def _get_tls_context ( self ) -> ssl . SSLContext : if self . tls_context is not None : context = self . tls_context else : # SERVER_AUTH is what we want for a client side socket context = ssl . create_default_context ( ssl . Purpose . SERVER_AUTH ) context . check_hostname = bool ( self . validate_certs ) if self . validate_certs : context . verify_mode = ssl . CERT_REQUIRED else : context . verify_mode = ssl . CERT_NONE if self . cert_bundle is not None : context . load_verify_locations ( cafile = self . cert_bundle ) if self . client_cert is not None : context . load_cert_chain ( self . client_cert , keyfile = self . client_key ) return context | Build an SSLContext object from the options we ve been given . | 197 | 13 |
234,228 | def _raise_error_if_disconnected ( self ) -> None : if ( self . transport is None or self . protocol is None or self . transport . is_closing ( ) ) : self . close ( ) raise SMTPServerDisconnected ( "Disconnected from SMTP server" ) | See if we re still connected and if not raise SMTPServerDisconnected . | 63 | 16 |
234,229 | async def sendmail ( self , sender : str , recipients : RecipientsType , message : Union [ str , bytes ] , mail_options : Iterable [ str ] = None , rcpt_options : Iterable [ str ] = None , timeout : DefaultNumType = _default , ) -> SendmailResponseType : if isinstance ( recipients , str ) : recipients = [ recipients ] else : recipients = list ( recipients ) if mail_options is None : mail_options = [ ] else : mail_options = list ( mail_options ) if rcpt_options is None : rcpt_options = [ ] else : rcpt_options = list ( rcpt_options ) async with self . _sendmail_lock : if self . supports_extension ( "size" ) : size_option = "size={}" . format ( len ( message ) ) mail_options . append ( size_option ) try : await self . mail ( sender , options = mail_options , timeout = timeout ) recipient_errors = await self . _send_recipients ( recipients , options = rcpt_options , timeout = timeout ) response = await self . data ( message , timeout = timeout ) except ( SMTPResponseException , SMTPRecipientsRefused ) as exc : # If we got an error, reset the envelope. try : await self . rset ( timeout = timeout ) except ( ConnectionError , SMTPResponseException ) : # If we're disconnected on the reset, or we get a bad # status, don't raise that as it's confusing pass raise exc return recipient_errors , response . message | This command performs an entire mail transaction . | 346 | 8 |
234,230 | def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result | Utility method to run commands synchronously for testing . | 129 | 11 |
234,231 | def check_announcements ( ) : res = requests . get ( "https://cs50.me/status/submit50" ) # TODO change this to submit50.io! if res . status_code == 200 and res . text . strip ( ) : raise Error ( res . text . strip ( ) ) | Check for any announcements from cs50 . me raise Error if so . | 68 | 14 |
234,232 | def check_version ( ) : # Retrieve version info res = requests . get ( "https://cs50.me/versions/submit50" ) # TODO change this to submit50.io! if res . status_code != 200 : raise Error ( _ ( "You have an unknown version of submit50. " "Email sysadmins@cs50.harvard.edu!" ) ) # Check that latest version == version installed required_required = pkg_resources . parse_version ( res . text . strip ( ) ) | Check that submit50 is the latest version according to submit50 . io . | 113 | 15 |
234,233 | def excepthook ( type , value , tb ) : if ( issubclass ( type , Error ) or issubclass ( type , lib50 . Error ) ) and str ( value ) : for line in str ( value ) . split ( "\n" ) : cprint ( str ( line ) , "yellow" ) else : cprint ( _ ( "Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!" ) , "yellow" ) if excepthook . verbose : traceback . print_exception ( type , value , tb ) cprint ( _ ( "Submission cancelled." ) , "red" ) | Report an exception . | 144 | 4 |
234,234 | def generate_transaction_id ( stmt_line ) : return str ( abs ( hash ( ( stmt_line . date , stmt_line . memo , stmt_line . amount ) ) ) ) | Generate pseudo - unique id for given statement line . | 46 | 11 |
234,235 | def recalculate_balance ( stmt ) : total_amount = sum ( sl . amount for sl in stmt . lines ) stmt . start_balance = stmt . start_balance or D ( 0 ) stmt . end_balance = stmt . start_balance + total_amount stmt . start_date = min ( sl . date for sl in stmt . lines ) stmt . end_date = max ( sl . date for sl in stmt . lines ) | Recalculate statement starting and ending dates and balances . | 103 | 12 |
234,236 | def assert_valid ( self ) : assert self . trntype in TRANSACTION_TYPES , "trntype must be one of %s" % TRANSACTION_TYPES if self . bank_account_to : self . bank_account_to . assert_valid ( ) | Ensure that fields have valid values | 62 | 7 |
234,237 | def parse ( self ) : reader = self . split_records ( ) for line in reader : self . cur_record += 1 if not line : continue stmt_line = self . parse_record ( line ) if stmt_line : stmt_line . assert_valid ( ) self . statement . lines . append ( stmt_line ) return self . statement | Read and parse statement | 79 | 4 |
234,238 | def acquire_auth_token_ticket ( self , headers = None ) : logging . debug ( '[CAS] Acquiring Auth token ticket' ) url = self . _get_auth_token_tickets_url ( ) text = self . _perform_post ( url , headers = headers ) auth_token_ticket = json . loads ( text ) [ 'ticket' ] logging . debug ( '[CAS] Acquire Auth token ticket: {}' . format ( auth_token_ticket ) ) return auth_token_ticket | Acquire an auth token from the CAS server . | 113 | 10 |
234,239 | def create_session ( self , ticket , payload = None , expires = None ) : assert isinstance ( self . session_storage_adapter , CASSessionAdapter ) logging . debug ( '[CAS] Creating session for ticket {}' . format ( ticket ) ) self . session_storage_adapter . create ( ticket , payload = payload , expires = expires , ) | Create a session record from a service ticket . | 78 | 9 |
234,240 | def delete_session ( self , ticket ) : assert isinstance ( self . session_storage_adapter , CASSessionAdapter ) logging . debug ( '[CAS] Deleting session for ticket {}' . format ( ticket ) ) self . session_storage_adapter . delete ( ticket ) | Delete a session record associated with a service ticket . | 62 | 10 |
234,241 | def get_api_url ( self , api_resource , auth_token_ticket , authenticator , private_key , service_url = None , * * kwargs ) : auth_token , auth_token_signature = self . _build_auth_token_data ( auth_token_ticket , authenticator , private_key , * * kwargs ) params = { 'at' : auth_token , 'ats' : auth_token_signature , } if service_url is not None : params [ 'service' ] = service_url url = '{}?{}' . format ( self . _get_api_url ( api_resource ) , urlencode ( params ) , ) return url | Build an auth - token - protected CAS API url . | 157 | 11 |
234,242 | def get_auth_token_login_url ( self , auth_token_ticket , authenticator , private_key , service_url , username , ) : auth_token , auth_token_signature = self . _build_auth_token_data ( auth_token_ticket , authenticator , private_key , username = username , ) logging . debug ( '[CAS] AuthToken: {}' . format ( auth_token ) ) url = self . _get_auth_token_login_url ( auth_token = auth_token , auth_token_signature = auth_token_signature , service_url = service_url , ) logging . debug ( '[CAS] AuthToken Login URL: {}' . format ( url ) ) return url | Build an auth token login URL . | 164 | 7 |
234,243 | def parse_logout_request ( self , message_text ) : result = { } xml_document = parseString ( message_text ) for node in xml_document . getElementsByTagName ( 'saml:NameId' ) : for child in node . childNodes : if child . nodeType == child . TEXT_NODE : result [ 'name_id' ] = child . nodeValue . strip ( ) for node in xml_document . getElementsByTagName ( 'samlp:SessionIndex' ) : for child in node . childNodes : if child . nodeType == child . TEXT_NODE : result [ 'session_index' ] = str ( child . nodeValue . strip ( ) ) for key in xml_document . documentElement . attributes . keys ( ) : result [ str ( key ) ] = str ( xml_document . documentElement . getAttribute ( key ) ) logging . debug ( '[CAS] LogoutRequest:\n{}' . format ( json . dumps ( result , sort_keys = True , indent = 4 , separators = [ ',' , ': ' ] ) , ) ) return result | Parse the contents of a CAS LogoutRequest XML message . | 248 | 13 |
234,244 | def perform_api_request ( self , url , method = 'POST' , headers = None , body = None , * * kwargs ) : assert method in ( 'GET' , 'POST' ) if method == 'GET' : response = self . _perform_get ( url , headers = headers , * * kwargs ) elif method == 'POST' : response = self . _perform_post ( url , headers = headers , data = body , * * kwargs ) return response | Perform an auth - token - protected request against a CAS API endpoint . | 109 | 15 |
234,245 | def perform_proxy ( self , proxy_ticket , headers = None ) : url = self . _get_proxy_url ( ticket = proxy_ticket ) logging . debug ( '[CAS] Proxy URL: {}' . format ( url ) ) return self . _perform_cas_call ( url , ticket = proxy_ticket , headers = headers , ) | Fetch a response from the remote CAS proxy endpoint . | 76 | 11 |
234,246 | def perform_proxy_validate ( self , proxied_service_ticket , headers = None ) : url = self . _get_proxy_validate_url ( ticket = proxied_service_ticket ) logging . debug ( '[CAS] ProxyValidate URL: {}' . format ( url ) ) return self . _perform_cas_call ( url , ticket = proxied_service_ticket , headers = headers , ) | Fetch a response from the remote CAS proxyValidate endpoint . | 93 | 13 |
234,247 | def perform_service_validate ( self , ticket = None , service_url = None , headers = None , ) : url = self . _get_service_validate_url ( ticket , service_url = service_url ) logging . debug ( '[CAS] ServiceValidate URL: {}' . format ( url ) ) return self . _perform_cas_call ( url , ticket = ticket , headers = headers ) | Fetch a response from the remote CAS serviceValidate endpoint . | 92 | 13 |
234,248 | def session_exists ( self , ticket ) : assert isinstance ( self . session_storage_adapter , CASSessionAdapter ) exists = self . session_storage_adapter . exists ( ticket ) logging . debug ( '[CAS] Session [{}] exists: {}' . format ( ticket , exists ) ) return exists | Test if a session records exists for a service ticket . | 71 | 11 |
234,249 | def create ( self , ticket , payload = None , expires = None ) : if not payload : payload = True self . _client . set ( str ( ticket ) , payload , expires ) | Create a session identifier in memcache associated with ticket . | 39 | 11 |
234,250 | def __check_response ( self , msg ) : if not isinstance ( msg , list ) : msg = msg . split ( "\n" ) if ( len ( msg ) > 2 ) and self . RE_PATTERNS [ 'not_allowed_pattern' ] . match ( msg [ 2 ] ) : raise NotAllowed ( msg [ 2 ] [ 2 : ] ) if self . RE_PATTERNS [ 'credentials_required_pattern' ] . match ( msg [ 0 ] ) : raise AuthorizationError ( 'Credentials required.' ) if self . RE_PATTERNS [ 'syntax_error_pattern' ] . match ( msg [ 0 ] ) : raise APISyntaxError ( msg [ 2 ] [ 2 : ] if len ( msg ) > 2 else 'Syntax error.' ) if self . RE_PATTERNS [ 'bad_request_pattern' ] . match ( msg [ 0 ] ) : raise BadRequest ( msg [ 3 ] if len ( msg ) > 2 else 'Bad request.' ) | Search general errors in server response and raise exceptions when found . | 226 | 12 |
234,251 | def __normalize_list ( self , msg ) : if isinstance ( msg , list ) : msg = "" . join ( msg ) return list ( map ( lambda x : x . strip ( ) , msg . split ( "," ) ) ) | Split message to list by commas and trim whitespace . | 52 | 12 |
234,252 | def login ( self , login = None , password = None ) : if ( login is not None ) and ( password is not None ) : login_data = { 'user' : login , 'pass' : password } elif ( self . default_login is not None ) and ( self . default_password is not None ) : login_data = { 'user' : self . default_login , 'pass' : self . default_password } elif self . session . auth : login_data = None else : raise AuthorizationError ( 'Credentials required, fill login and password.' ) try : self . login_result = self . __get_status_code ( self . __request ( '' , post_data = login_data , without_login = True ) ) == 200 except AuthorizationError : # This happens when HTTP Basic or Digest authentication fails, but # we will not raise the error but just return False to indicate # invalid credentials return False return self . login_result | Login with default or supplied credetials . | 207 | 9 |
234,253 | def logout ( self ) : ret = False if self . login_result is True : ret = self . __get_status_code ( self . __request ( 'logout' ) ) == 200 self . login_result = None return ret | Logout of user . | 52 | 5 |
234,254 | def new_correspondence ( self , queue = None ) : return self . search ( Queue = queue , order = '-LastUpdated' , LastUpdatedBy__notexact = self . default_login ) | Obtains tickets changed by other users than the system one . | 46 | 12 |
234,255 | def last_updated ( self , since , queue = None ) : return self . search ( Queue = queue , order = '-LastUpdated' , LastUpdatedBy__notexact = self . default_login , LastUpdated__gt = since ) | Obtains tickets changed after given date . | 53 | 8 |
234,256 | def get_ticket ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/show' . format ( str ( ticket_id ) , ) ) status_code = self . __get_status_code ( msg ) if status_code == 200 : pairs = { } msg = msg . split ( '\n' ) if ( len ( msg ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( msg [ 2 ] ) : return None req_matching = [ i for i , m in enumerate ( msg ) if self . RE_PATTERNS [ 'requestors_pattern' ] . match ( m ) ] req_id = req_matching [ 0 ] if req_matching else None if not req_id : raise UnexpectedMessageFormat ( 'Missing line starting with `Requestors:`.' ) for i in range ( req_id ) : if ': ' in msg [ i ] : header , content = self . split_header ( msg [ i ] ) pairs [ header . strip ( ) ] = content . strip ( ) requestors = [ msg [ req_id ] [ 12 : ] ] req_id += 1 while ( req_id < len ( msg ) ) and ( msg [ req_id ] [ : 12 ] == ' ' * 12 ) : requestors . append ( msg [ req_id ] [ 12 : ] ) req_id += 1 pairs [ 'Requestors' ] = self . __normalize_list ( requestors ) for i in range ( req_id , len ( msg ) ) : if ': ' in msg [ i ] : header , content = self . split_header ( msg [ i ] ) pairs [ header . strip ( ) ] = content . strip ( ) if 'Cc' in pairs : pairs [ 'Cc' ] = self . __normalize_list ( pairs [ 'Cc' ] ) if 'AdminCc' in pairs : pairs [ 'AdminCc' ] = self . __normalize_list ( pairs [ 'AdminCc' ] ) if 'id' not in pairs and not pairs [ 'id' ] . startswitch ( 'ticket/' ) : raise UnexpectedMessageFormat ( 'Response from RT didn\'t contain a valid ticket_id' ) else : pairs [ 'numerical_id' ] = pairs [ 'id' ] . split ( 'ticket/' ) [ 1 ] return pairs else : raise UnexpectedMessageFormat ( 'Received status code is {:d} instead of 200.' . format ( status_code ) ) | Fetch ticket by its ID . | 565 | 7 |
234,257 | def create_ticket ( self , Queue = None , files = [ ] , * * kwargs ) : post_data = 'id: ticket/new\nQueue: {}\n' . format ( Queue or self . default_queue , ) for key in kwargs : if key [ : 4 ] == 'Text' : post_data += "{}: {}\n" . format ( key , re . sub ( r'\n' , r'\n ' , kwargs [ key ] ) ) elif key [ : 3 ] == 'CF_' : post_data += "CF.{{{}}}: {}\n" . format ( key [ 3 : ] , kwargs [ key ] ) else : post_data += "{}: {}\n" . format ( key , kwargs [ key ] ) for file_info in files : post_data += "\nAttachment: {}" . format ( file_info [ 0 ] , ) msg = self . __request ( 'ticket/new' , post_data = { 'content' : post_data } , files = files ) for line in msg . split ( '\n' ) [ 2 : - 1 ] : res = self . RE_PATTERNS [ 'ticket_created_pattern' ] . match ( line ) if res is not None : return int ( res . group ( 1 ) ) warnings . warn ( line [ 2 : ] ) return - 1 | Create new ticket and set given parameters . | 312 | 8 |
234,258 | def edit_ticket ( self , ticket_id , * * kwargs ) : post_data = '' for key , value in iteritems ( kwargs ) : if isinstance ( value , ( list , tuple ) ) : value = ", " . join ( value ) if key [ : 3 ] != 'CF_' : post_data += "{}: {}\n" . format ( key , value ) else : post_data += "CF.{{{}}}: {}\n" . format ( key [ 3 : ] , value ) msg = self . __request ( 'ticket/{}/edit' . format ( str ( ticket_id ) ) , post_data = { 'content' : post_data } ) state = msg . split ( '\n' ) [ 2 ] return self . RE_PATTERNS [ 'update_pattern' ] . match ( state ) is not None | Edit ticket values . | 193 | 4 |
234,259 | def get_history ( self , ticket_id , transaction_id = None ) : if transaction_id is None : # We are using "long" format to get all history items at once. # Each history item is then separated by double dash. msgs = self . __request ( 'ticket/{}/history?format=l' . format ( str ( ticket_id ) , ) ) else : msgs = self . __request ( 'ticket/{}/history/id/{}' . format ( str ( ticket_id ) , str ( transaction_id ) ) ) lines = msgs . split ( '\n' ) if ( len ( lines ) > 2 ) and ( self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) or self . RE_PATTERNS [ 'not_related_pattern' ] . match ( lines [ 2 ] ) ) : return None msgs = msgs . split ( '\n--\n' ) items = [ ] for msg in msgs : pairs = { } msg = msg . split ( '\n' ) cont_matching = [ i for i , m in enumerate ( msg ) if self . RE_PATTERNS [ 'content_pattern' ] . match ( m ) ] cont_id = cont_matching [ 0 ] if cont_matching else None if not cont_id : raise UnexpectedMessageFormat ( 'Unexpected history entry. \ Missing line starting with `Content:`.' ) atta_matching = [ i for i , m in enumerate ( msg ) if self . RE_PATTERNS [ 'attachments_pattern' ] . match ( m ) ] atta_id = atta_matching [ 0 ] if atta_matching else None if not atta_id : raise UnexpectedMessageFormat ( 'Unexpected attachment part of history entry. \ Missing line starting with `Attachements:`.' ) for i in range ( cont_id ) : if ': ' in msg [ i ] : header , content = self . split_header ( msg [ i ] ) pairs [ header . strip ( ) ] = content . strip ( ) content = msg [ cont_id ] [ 9 : ] cont_id += 1 while ( cont_id < len ( msg ) ) and ( msg [ cont_id ] [ : 9 ] == ' ' * 9 ) : content += '\n' + msg [ cont_id ] [ 9 : ] cont_id += 1 pairs [ 'Content' ] = content for i in range ( cont_id , atta_id ) : if ': ' in msg [ i ] : header , content = self . split_header ( msg [ i ] ) pairs [ header . strip ( ) ] = content . strip ( ) attachments = [ ] for i in range ( atta_id + 1 , len ( msg ) ) : if ': ' in msg [ i ] : header , content = self . split_header ( msg [ i ] ) attachments . append ( ( int ( header ) , content . strip ( ) ) ) pairs [ 'Attachments' ] = attachments items . append ( pairs ) return items | Get set of history items . | 690 | 6 |
234,260 | def get_short_history ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/history' . format ( str ( ticket_id ) , ) ) items = [ ] lines = msg . split ( '\n' ) multiline_buffer = "" in_multiline = False if self . __get_status_code ( lines [ 0 ] ) == 200 : if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) : return None if len ( lines ) >= 4 : for line in lines [ 4 : ] : if line == "" : if not in_multiline : # start of multiline block in_multiline = True else : # end of multiline block line = multiline_buffer multiline_buffer = "" in_multiline = False else : if in_multiline : multiline_buffer += line line = "" if ': ' in line : hist_id , desc = line . split ( ': ' , 1 ) items . append ( ( int ( hist_id ) , desc ) ) return items | Get set of short history items | 261 | 6 |
234,261 | def reply ( self , ticket_id , text = '' , cc = '' , bcc = '' , content_type = 'text/plain' , files = [ ] ) : return self . __correspond ( ticket_id , text , 'correspond' , cc , bcc , content_type , files ) | Sends email message to the contacts in Requestors field of given ticket with subject as is set in Subject field . | 67 | 23 |
234,262 | def get_attachments ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/attachments' . format ( str ( ticket_id ) , ) ) lines = msg . split ( '\n' ) if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) : return None attachment_infos = [ ] if ( self . __get_status_code ( lines [ 0 ] ) == 200 ) and ( len ( lines ) >= 4 ) : for line in lines [ 4 : ] : info = self . RE_PATTERNS [ 'attachments_list_pattern' ] . match ( line ) if info : attachment_infos . append ( info . groups ( ) ) return attachment_infos | Get attachment list for a given ticket | 183 | 7 |
234,263 | def get_attachments_ids ( self , ticket_id ) : attachments = self . get_attachments ( ticket_id ) return [ int ( at [ 0 ] ) for at in attachments ] if attachments else attachments | Get IDs of attachments for given ticket . | 46 | 8 |
234,264 | def get_attachment ( self , ticket_id , attachment_id ) : msg = self . __request ( 'ticket/{}/attachments/{}' . format ( str ( ticket_id ) , str ( attachment_id ) ) , text_response = False ) msg = msg . split ( b'\n' ) if ( len ( msg ) > 2 ) and ( self . RE_PATTERNS [ 'invalid_attachment_pattern_bytes' ] . match ( msg [ 2 ] ) or self . RE_PATTERNS [ 'does_not_exist_pattern_bytes' ] . match ( msg [ 2 ] ) ) : return None msg = msg [ 2 : ] head_matching = [ i for i , m in enumerate ( msg ) if self . RE_PATTERNS [ 'headers_pattern_bytes' ] . match ( m ) ] head_id = head_matching [ 0 ] if head_matching else None if not head_id : raise UnexpectedMessageFormat ( 'Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.' ) msg [ head_id ] = re . sub ( b'^Headers: (.*)$' , r'\1' , msg [ head_id ] ) cont_matching = [ i for i , m in enumerate ( msg ) if self . RE_PATTERNS [ 'content_pattern_bytes' ] . match ( m ) ] cont_id = cont_matching [ 0 ] if cont_matching else None if not cont_matching : raise UnexpectedMessageFormat ( 'Unexpected content part of attachment entry. \ Missing line starting with `Content:`.' ) pairs = { } for i in range ( head_id ) : if b': ' in msg [ i ] : header , content = msg [ i ] . split ( b': ' , 1 ) pairs [ header . strip ( ) . decode ( 'utf-8' ) ] = content . strip ( ) . decode ( 'utf-8' ) headers = { } for i in range ( head_id , cont_id ) : if b': ' in msg [ i ] : header , content = msg [ i ] . split ( b': ' , 1 ) headers [ header . strip ( ) . decode ( 'utf-8' ) ] = content . strip ( ) . decode ( 'utf-8' ) pairs [ 'Headers' ] = headers content = msg [ cont_id ] [ 9 : ] for i in range ( cont_id + 1 , len ( msg ) ) : if msg [ i ] [ : 9 ] == ( b' ' * 9 ) : content += b'\n' + msg [ i ] [ 9 : ] pairs [ 'Content' ] = content return pairs | Get attachment . | 605 | 3 |
234,265 | def get_attachment_content ( self , ticket_id , attachment_id ) : msg = self . __request ( 'ticket/{}/attachments/{}/content' . format ( str ( ticket_id ) , str ( attachment_id ) ) , text_response = False ) lines = msg . split ( b'\n' , 3 ) if ( len ( lines ) == 4 ) and ( self . RE_PATTERNS [ 'invalid_attachment_pattern_bytes' ] . match ( lines [ 2 ] ) or self . RE_PATTERNS [ 'does_not_exist_pattern_bytes' ] . match ( lines [ 2 ] ) ) : return None return msg [ msg . find ( b'\n' ) + 2 : - 3 ] | Get content of attachment without headers . | 171 | 7 |
234,266 | def get_user ( self , user_id ) : msg = self . __request ( 'user/{}' . format ( str ( user_id ) , ) ) status_code = self . __get_status_code ( msg ) if ( status_code == 200 ) : pairs = { } lines = msg . split ( '\n' ) if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) : return None for line in lines [ 2 : ] : if ': ' in line : header , content = line . split ( ': ' , 1 ) pairs [ header . strip ( ) ] = content . strip ( ) return pairs else : raise UnexpectedMessageFormat ( 'Received status code is {:d} instead of 200.' . format ( status_code ) ) | Get user details . | 191 | 4 |
234,267 | def get_links ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/links/show' . format ( str ( ticket_id ) , ) ) status_code = self . __get_status_code ( msg ) if ( status_code == 200 ) : pairs = { } msg = msg . split ( '\n' ) if ( len ( msg ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( msg [ 2 ] ) : return None i = 2 while i < len ( msg ) : if ': ' in msg [ i ] : key , link = self . split_header ( msg [ i ] ) links = [ link . strip ( ) ] j = i + 1 pad = len ( key ) + 2 # loop over next lines for the same key while ( j < len ( msg ) ) and msg [ j ] . startswith ( ' ' * pad ) : links [ - 1 ] = links [ - 1 ] [ : - 1 ] # remove trailing comma from previous item links . append ( msg [ j ] [ pad : ] . strip ( ) ) j += 1 pairs [ key ] = links i = j - 1 i += 1 return pairs else : raise UnexpectedMessageFormat ( 'Received status code is {:d} instead of 200.' . format ( status_code ) ) | Gets the ticket links for a single ticket . | 300 | 10 |
234,268 | def edit_ticket_links ( self , ticket_id , * * kwargs ) : post_data = '' for key in kwargs : post_data += "{}: {}\n" . format ( key , str ( kwargs [ key ] ) ) msg = self . __request ( 'ticket/{}/links' . format ( str ( ticket_id ) , ) , post_data = { 'content' : post_data } ) state = msg . split ( '\n' ) [ 2 ] return self . RE_PATTERNS [ 'links_updated_pattern' ] . match ( state ) is not None | Edit ticket links . | 138 | 4 |
234,269 | def split_header ( line ) : match = re . match ( r'^(CF\.\{.*?}): (.*)$' , line ) if match : return ( match . group ( 1 ) , match . group ( 2 ) ) return line . split ( ': ' , 1 ) | Split a header line into field name and field value . | 64 | 11 |
234,270 | def PrivateKeyFromWIF ( wif ) : if wif is None or len ( wif ) is not 52 : raise ValueError ( 'Please provide a wif with a length of 52 bytes (LEN: {0:d})' . format ( len ( wif ) ) ) data = base58 . b58decode ( wif ) length = len ( data ) if length is not 38 or data [ 0 ] is not 0x80 or data [ 33 ] is not 0x01 : raise ValueError ( "Invalid format!" ) checksum = Crypto . Hash256 ( data [ 0 : 34 ] ) [ 0 : 4 ] if checksum != data [ 34 : ] : raise ValueError ( "Invalid WIF Checksum!" ) return data [ 1 : 33 ] | Get the private key from a WIF key | 165 | 9 |
234,271 | def PrivateKeyFromNEP2 ( nep2_key , passphrase ) : if not nep2_key or len ( nep2_key ) != 58 : raise ValueError ( 'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})' . format ( len ( nep2_key ) ) ) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len ( NEP_FLAG ) + len ( NEP_HEADER ) try : decoded_key = base58 . b58decode_check ( nep2_key ) except Exception as e : raise ValueError ( "Invalid nep2_key" ) address_hash = decoded_key [ ADDRESS_HASH_OFFSET : ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE ] encrypted = decoded_key [ - 32 : ] pwd_normalized = bytes ( unicodedata . normalize ( 'NFC' , passphrase ) , 'utf-8' ) derived = scrypt . hash ( pwd_normalized , address_hash , N = SCRYPT_ITERATIONS , r = SCRYPT_BLOCKSIZE , p = SCRYPT_PARALLEL_FACTOR , buflen = SCRYPT_KEY_LEN_BYTES ) derived1 = derived [ : 32 ] derived2 = derived [ 32 : ] cipher = AES . new ( derived2 , AES . MODE_ECB ) decrypted = cipher . decrypt ( encrypted ) private_key = xor_bytes ( decrypted , derived1 ) # Now check that the address hashes match. If they don't, the password was wrong. kp_new = KeyPair ( priv_key = private_key ) kp_new_address = kp_new . GetAddress ( ) kp_new_address_hash_tmp = hashlib . sha256 ( kp_new_address . encode ( "utf-8" ) ) . digest ( ) kp_new_address_hash_tmp2 = hashlib . sha256 ( kp_new_address_hash_tmp ) . digest ( ) kp_new_address_hash = kp_new_address_hash_tmp2 [ : 4 ] if ( kp_new_address_hash != address_hash ) : raise ValueError ( "Wrong passphrase" ) return private_key | Gets the private key from a NEP - 2 encrypted private key | 533 | 14 |
234,272 | def GetAddress ( self ) : script = b'21' + self . PublicKey . encode_point ( True ) + b'ac' script_hash = Crypto . ToScriptHash ( script ) address = Crypto . ToAddress ( script_hash ) return address | Returns the public NEO address for this KeyPair | 55 | 10 |
234,273 | def Export ( self ) : data = bytearray ( 38 ) data [ 0 ] = 0x80 data [ 1 : 33 ] = self . PrivateKey [ 0 : 32 ] data [ 33 ] = 0x01 checksum = Crypto . Default ( ) . Hash256 ( data [ 0 : 34 ] ) data [ 34 : 38 ] = checksum [ 0 : 4 ] b58 = base58 . b58encode ( bytes ( data ) ) return b58 . decode ( "utf-8" ) | Export this KeyPair s private key in WIF format . | 108 | 13 |
234,274 | def ExportNEP2 ( self , passphrase ) : if len ( passphrase ) < 2 : raise ValueError ( "Passphrase must have a minimum of 2 characters" ) # Hash address twice, then only use the first 4 bytes address_hash_tmp = hashlib . sha256 ( self . GetAddress ( ) . encode ( "utf-8" ) ) . digest ( ) address_hash_tmp2 = hashlib . sha256 ( address_hash_tmp ) . digest ( ) address_hash = address_hash_tmp2 [ : 4 ] # Normalize password and run scrypt over it with the address_hash pwd_normalized = bytes ( unicodedata . normalize ( 'NFC' , passphrase ) , 'utf-8' ) derived = scrypt . hash ( pwd_normalized , address_hash , N = SCRYPT_ITERATIONS , r = SCRYPT_BLOCKSIZE , p = SCRYPT_PARALLEL_FACTOR , buflen = SCRYPT_KEY_LEN_BYTES ) # Split the scrypt-result into two parts derived1 = derived [ : 32 ] derived2 = derived [ 32 : ] # Run XOR and encrypt the derived parts with AES xor_ed = xor_bytes ( bytes ( self . PrivateKey ) , derived1 ) cipher = AES . new ( derived2 , AES . MODE_ECB ) encrypted = cipher . encrypt ( xor_ed ) # Assemble the final result assembled = bytearray ( ) assembled . extend ( NEP_HEADER ) assembled . extend ( NEP_FLAG ) assembled . extend ( address_hash ) assembled . extend ( encrypted ) # Finally, encode with Base58Check encrypted_key_nep2 = base58 . b58encode_check ( bytes ( assembled ) ) return encrypted_key_nep2 . decode ( "utf-8" ) | Export the encrypted private key in NEP - 2 format . | 415 | 12 |
234,275 | def ReadByte ( self , do_ord = True ) : try : if do_ord : return ord ( self . stream . read ( 1 ) ) return self . stream . read ( 1 ) except Exception as e : logger . error ( "ord expected character but got none" ) return 0 | Read a single byte . | 61 | 5 |
234,276 | def SafeReadBytes ( self , length ) : data = self . ReadBytes ( length ) if len ( data ) < length : raise ValueError ( "Not enough data available" ) else : return data | Read exactly length number of bytes from the stream . | 42 | 10 |
234,277 | def ToScriptHash ( data , unhex = True ) : if len ( data ) > 1 and unhex : data = binascii . unhexlify ( data ) return UInt160 ( data = binascii . unhexlify ( bytes ( Crypto . Hash160 ( data ) , encoding = 'utf-8' ) ) ) | Get a script hash of the data . | 75 | 8 |
234,278 | def Sign ( message , private_key ) : hash = hashlib . sha256 ( binascii . unhexlify ( message ) ) . hexdigest ( ) v , r , s = bitcoin . ecdsa_raw_sign ( hash , private_key ) rb = bytearray ( r . to_bytes ( 32 , 'big' ) ) sb = bytearray ( s . to_bytes ( 32 , 'big' ) ) sig = rb + sb return sig | Sign the message with the given private key . | 111 | 9 |
234,279 | def sqrt ( self , val , flag ) : if val . iszero ( ) : return val sw = self . p % 8 if sw == 3 or sw == 7 : res = val ** ( ( self . p + 1 ) / 4 ) elif sw == 5 : x = val ** ( ( self . p + 1 ) / 4 ) if x == 1 : res = val ** ( ( self . p + 3 ) / 8 ) else : res = ( 4 * val ) ** ( ( self . p - 5 ) / 8 ) * 2 * val else : raise Exception ( "modsqrt non supported for (p%8)==1" ) if res . value % 2 == flag : return res else : return - res | calculate the square root modulus p | 155 | 9 |
234,280 | def value ( self , x ) : return x if isinstance ( x , FiniteField . Value ) and x . field == self else FiniteField . Value ( self , x ) | converts an integer or FinitField . Value to a value of this FiniteField . | 39 | 19 |
234,281 | def integer ( self , x ) : if type ( x ) is str : hex = binascii . unhexlify ( x ) return int . from_bytes ( hex , 'big' ) return x . value if isinstance ( x , FiniteField . Value ) else x | returns a plain integer | 61 | 5 |
234,282 | def add ( self , p , q ) : if p . iszero ( ) : return q if q . iszero ( ) : return p lft = 0 # calculate the slope of the intersection line if p == q : if p . y == 0 : return self . zero ( ) lft = ( 3 * p . x ** 2 + self . a ) / ( 2 * p . y ) elif p . x == q . x : return self . zero ( ) else : lft = ( p . y - q . y ) / ( p . x - q . x ) # calculate the intersection point x = lft ** 2 - ( p . x + q . x ) y = lft * ( p . x - x ) - p . y return self . point ( x , y ) | perform elliptic curve addition | 170 | 6 |
234,283 | def point ( self , x , y ) : return EllipticCurve . ECPoint ( self , self . field . value ( x ) , self . field . value ( y ) ) | construct a point from 2 values | 41 | 6 |
234,284 | def isoncurve ( self , p ) : return p . iszero ( ) or p . y ** 2 == p . x ** 3 + self . a * p . x + self . b | verifies if a point is on the curve | 42 | 9 |
234,285 | def secp256r1 ( ) : GFp = FiniteField ( int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF" , 16 ) ) ec = EllipticCurve ( GFp , 115792089210356248762697446949407573530086143415290314195533631308867097853948 , 41058363725152142129326129780047268409114441015993725554835256314039467401291 ) # return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) return ECDSA ( ec , ec . point ( 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 , 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 ) , GFp ) | create the secp256r1 curve | 342 | 8 |
234,286 | def decode_secp256r1 ( str , unhex = True , check_on_curve = True ) : GFp = FiniteField ( int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF" , 16 ) ) ec = EllipticCurve ( GFp , 115792089210356248762697446949407573530086143415290314195533631308867097853948 , 41058363725152142129326129780047268409114441015993725554835256314039467401291 ) point = ec . decode_from_hex ( str , unhex = unhex ) if check_on_curve : if point . isoncurve ( ) : return ECDSA ( GFp , point , int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC" , 16 ) ) else : raise Exception ( "Could not decode string" ) return ECDSA ( GFp , point , int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC" , 16 ) ) | decode a public key on the secp256r1 curve | 243 | 13 |
234,287 | def secp256k1 ( ) : GFp = FiniteField ( 2 ** 256 - 2 ** 32 - 977 ) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve ( GFp , 0 , 7 ) return ECDSA ( ec , ec . point ( 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 , 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 ) , 2 ** 256 - 432420386565659656852420866394968145599 ) | create the secp256k1 curve | 185 | 8 |
234,288 | def isValidPublicAddress ( address : str ) -> bool : valid = False if len ( address ) == 34 and address [ 0 ] == 'A' : try : base58 . b58decode_check ( address . encode ( ) ) valid = True except ValueError : # checksum mismatch valid = False return valid | Check if address is a valid NEO address | 67 | 8 |
234,289 | def __Build ( leaves ) : if len ( leaves ) < 1 : raise Exception ( 'Leaves must have length' ) if len ( leaves ) == 1 : return leaves [ 0 ] num_parents = int ( ( len ( leaves ) + 1 ) / 2 ) parents = [ MerkleTreeNode ( ) for i in range ( 0 , num_parents ) ] for i in range ( 0 , num_parents ) : node = parents [ i ] node . LeftChild = leaves [ i * 2 ] leaves [ i * 2 ] . Parent = node if ( i * 2 + 1 == len ( leaves ) ) : node . RightChild = node . LeftChild else : node . RightChild = leaves [ i * 2 + 1 ] leaves [ i * 2 + 1 ] . Parent = node hasharray = bytearray ( node . LeftChild . Hash . ToArray ( ) + node . RightChild . Hash . ToArray ( ) ) node . Hash = UInt256 ( data = Crypto . Hash256 ( hasharray ) ) return MerkleTree . __Build ( parents ) | Build the merkle tree . | 231 | 7 |
234,290 | def ComputeRoot ( hashes ) : if not len ( hashes ) : raise Exception ( 'Hashes must have length' ) if len ( hashes ) == 1 : return hashes [ 0 ] tree = MerkleTree ( hashes ) return tree . Root . Hash | Compute the root hash . | 54 | 6 |
234,291 | def ToHashArray ( self ) : hashes = set ( ) MerkleTree . __DepthFirstSearch ( self . Root , hashes ) return list ( hashes ) | Turn the tree into a list of hashes . | 34 | 9 |
234,292 | def Trim ( self , flags ) : logger . info ( "Trimming!" ) flags = bytearray ( flags ) length = 1 << self . Depth - 1 while len ( flags ) < length : flags . append ( 0 ) MerkleTree . _TrimNode ( self . Root , 0 , self . Depth , flags ) | Trim the nodes from the tree keeping only the root hash . | 72 | 13 |
234,293 | def _TrimNode ( node , index , depth , flags ) : if depth == 1 or node . LeftChild is None : return if depth == 2 : if not flags [ index * 2 ] and not flags [ index * 2 + 1 ] : node . LeftChild = None node . RightChild = None else : MerkleTree . _TrimNode ( node . LeftChild , index * 2 , depth - 1 , flags ) MerkleTree . _TrimNode ( node . RightChild , index * 2 , depth - 1 , flags ) if node . LeftChild . LeftChild is None and node . RightChild . RightChild is None : node . LeftChild = None node . RightChild = None | Internal helper method to trim a node . | 149 | 8 |
234,294 | def double_sha256 ( ba ) : d1 = hashlib . sha256 ( ba ) d2 = hashlib . sha256 ( ) d1 . hexdigest ( ) d2 . update ( d1 . digest ( ) ) return d2 . hexdigest ( ) | Perform two SHA256 operations on the input . | 61 | 10 |
234,295 | def scripthash_to_address ( scripthash ) : sb = bytearray ( [ ADDRESS_VERSION ] ) + scripthash c256 = bin_dbl_sha256 ( sb ) [ 0 : 4 ] outb = sb + bytearray ( c256 ) return base58 . b58encode ( bytes ( outb ) ) . decode ( "utf-8" ) | Convert a script hash to a public address . | 94 | 10 |
234,296 | def base256_encode ( n , minwidth = 0 ) : # int/long to byte array if n > 0 : arr = [ ] while n : n , rem = divmod ( n , 256 ) arr . append ( rem ) b = bytearray ( reversed ( arr ) ) elif n == 0 : b = bytearray ( b'\x00' ) else : raise ValueError ( "Negative numbers not supported" ) if minwidth > 0 and len ( b ) < minwidth : # zero padding needed? padding = ( minwidth - len ( b ) ) * b'\x00' b = bytearray ( padding ) + b b . reverse ( ) return b | Encode the input with base256 . | 152 | 8 |
234,297 | def xor_bytes ( a , b ) : assert isinstance ( a , bytes ) assert isinstance ( b , bytes ) assert len ( a ) == len ( b ) res = bytearray ( ) for i in range ( len ( a ) ) : res . append ( a [ i ] ^ b [ i ] ) return bytes ( res ) | XOR on two bytes objects | 75 | 6 |
234,298 | def WriteBytes ( self , value , unhex = True ) : if unhex : try : value = binascii . unhexlify ( value ) except binascii . Error : pass return self . stream . write ( value ) | Write a bytes type to the stream . | 52 | 8 |
234,299 | def WriteUInt160 ( self , value ) : if type ( value ) is UInt160 : value . Serialize ( self ) else : raise Exception ( "value must be UInt160 instance " ) | Write a UInt160 type to the stream . | 43 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.