{"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"util\/log_analyzer.py","language":"python","identifier":"_get_time","parameters":"(log)","argument_list":"","return_statement":"return datetime.strptime(tstamp, \"%Y-%m-%d %H:%M:%S\")","docstring":"Parse timestamp from log line","docstring_summary":"Parse timestamp from log line","docstring_tokens":["Parse","timestamp","from","log","line"],"function":"def _get_time(log):\n \"\"\"Parse timestamp from log line\"\"\"\n tstamp = log[:19]\n return datetime.strptime(tstamp, \"%Y-%m-%d %H:%M:%S\")","function_tokens":["def","_get_time","(","log",")",":","tstamp","=","log","[",":","19","]","return","datetime",".","strptime","(","tstamp",",","\"%Y-%m-%d %H:%M:%S\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/util\/log_analyzer.py#L17-L20"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"util\/log_analyzer.py","language":"python","identifier":"_parse","parameters":"(log, start_time)","argument_list":"","return_statement":"return info","docstring":"Parse logs in the format from monitor.py\n\n Args:\n log : String containing the logged line.\n start_time : Log file's starting time.\n\n Returns:\n Dictionary with the receiver metrics.","docstring_summary":"Parse logs in the format from monitor.py","docstring_tokens":["Parse","logs","in","the","format","from","monitor",".","py"],"function":"def _parse(log, start_time):\n \"\"\"Parse logs in the format from monitor.py\n\n Args:\n log : String containing the logged line.\n start_time : Log file's starting time.\n\n Returns:\n Dictionary with the receiver metrics.\n\n \"\"\"\n log_time = _get_time(log)\n info = {'date': log_time, 'time': (log_time - start_time).total_seconds()}\n for entry in log[19:-1].split(\";\"):\n key, val = entry.split(\"=\")\n key = key.strip()\n val = val.strip()\n\n if (key == \"Lock\"):\n val = \"Locked\" if val == \"True\" else \"Unlocked\" # categorial plot\n elif (key == \"Level\" or key == \"SNR\"):\n unit = re.sub('[0-9.-]', '', val)\n val = val.replace(unit, '')\n # The logs from the S400 could return NaN, in which case \"val\" is\n # empty here. Skip these values.\n if (val == ''):\n continue\n val = float(val)\n elif (key == \"BER\" or key == \"Packet Errors\"):\n val = float(val)\n else:\n raise ValueError(\"Unknown key\")\n\n info[key] = val\n\n return info","function_tokens":["def","_parse","(","log",",","start_time",")",":","log_time","=","_get_time","(","log",")","info","=","{","'date'",":","log_time",",","'time'",":","(","log_time","-","start_time",")",".","total_seconds","(",")","}","for","entry","in","log","[","19",":","-","1","]",".","split","(","\";\"",")",":","key",",","val","=","entry",".","split","(","\"=\"",")","key","=","key",".","strip","(",")","val","=","val",".","strip","(",")","if","(","key","==","\"Lock\"",")",":","val","=","\"Locked\"","if","val","==","\"True\"","else","\"Unlocked\"","# categorial plot","elif","(","key","==","\"Level\"","or","key","==","\"SNR\"",")",":","unit","=","re",".","sub","(","'[0-9.-]'",",","''",",","val",")","val","=","val",".","replace","(","unit",",","''",")","# The logs from the S400 could return NaN, in which case \"val\" is","# empty here. Skip these values.","if","(","val","==","''",")",":","continue","val","=","float","(","val",")","elif","(","key","==","\"BER\"","or","key","==","\"Packet Errors\"",")",":","val","=","float","(","val",")","else",":","raise","ValueError","(","\"Unknown key\"",")","info","[","key","]","=","val","return","info"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/util\/log_analyzer.py#L23-L58"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"util\/log_analyzer.py","language":"python","identifier":"_plot","parameters":"(ds, ds_name)","argument_list":"","return_statement":"","docstring":"Plot all results from list of dictionaries\n\n Args:\n ds : Dataset (list of dictionaries)\n ds_name : Dataset name","docstring_summary":"Plot all results from list of dictionaries","docstring_tokens":["Plot","all","results","from","list","of","dictionaries"],"function":"def _plot(ds, ds_name):\n \"\"\"Plot all results from list of dictionaries\n\n Args:\n ds : Dataset (list of dictionaries)\n ds_name : Dataset name\n\n \"\"\"\n keys = set()\n for elem in ds:\n keys.update(list(ds[0].keys()))\n keys.remove(\"time\")\n keys.remove(\"date\")\n\n formatter = DateFormatter('%m\/%d %H:%M')\n\n path = os.path.join(\"figs\", ds_name)\n if not os.path.isdir(path):\n os.makedirs(path)\n\n for key in keys:\n logger.info(\"Plotting {}\".format(key))\n\n x = [r[key] for r in ds if key in r]\n t = [r[\"date\"] for r in ds if key in r]\n\n # Add unit to y-label\n if (key == \"SNR\"):\n ylabel = \"SNR (dB)\"\n elif (key == \"Level\"):\n ylabel = \"Signal Level\"\n # NOTE: the SDR logs positive signal levels rather than dBm.\n if (all([val < 0 for val in x])):\n ylabel += \" (dBm)\"\n else:\n ylabel = key\n\n fig, ax = plt.subplots()\n plt.plot_date(t, x, ms=2)\n plt.ylabel(ylabel)\n plt.xlabel(\"Time (UTC)\")\n\n # Plot BER in log scale as it is not zero throughout the acquisition\n if (key == \"BER\" and any([val > 0 for val in x])):\n ax.set_yscale('log')\n\n ax.xaxis.set_major_formatter(formatter)\n ax.xaxis.set_tick_params(rotation=30, labelsize=10)\n plt.tight_layout()\n\n savepath = os.path.join(path, key.replace(\"\/\", \"_\").lower() + \".png\")\n plt.savefig(savepath, dpi=300)\n plt.close()","function_tokens":["def","_plot","(","ds",",","ds_name",")",":","keys","=","set","(",")","for","elem","in","ds",":","keys",".","update","(","list","(","ds","[","0","]",".","keys","(",")",")",")","keys",".","remove","(","\"time\"",")","keys",".","remove","(","\"date\"",")","formatter","=","DateFormatter","(","'%m\/%d %H:%M'",")","path","=","os",".","path",".","join","(","\"figs\"",",","ds_name",")","if","not","os",".","path",".","isdir","(","path",")",":","os",".","makedirs","(","path",")","for","key","in","keys",":","logger",".","info","(","\"Plotting {}\"",".","format","(","key",")",")","x","=","[","r","[","key","]","for","r","in","ds","if","key","in","r","]","t","=","[","r","[","\"date\"","]","for","r","in","ds","if","key","in","r","]","# Add unit to y-label","if","(","key","==","\"SNR\"",")",":","ylabel","=","\"SNR (dB)\"","elif","(","key","==","\"Level\"",")",":","ylabel","=","\"Signal Level\"","# NOTE: the SDR logs positive signal levels rather than dBm.","if","(","all","(","[","val","<","0","for","val","in","x","]",")",")",":","ylabel","+=","\" (dBm)\"","else",":","ylabel","=","key","fig",",","ax","=","plt",".","subplots","(",")","plt",".","plot_date","(","t",",","x",",","ms","=","2",")","plt",".","ylabel","(","ylabel",")","plt",".","xlabel","(","\"Time (UTC)\"",")","# Plot BER in log scale as it is not zero throughout the acquisition","if","(","key","==","\"BER\"","and","any","(","[","val",">","0","for","val","in","x","]",")",")",":","ax",".","set_yscale","(","'log'",")","ax",".","xaxis",".","set_major_formatter","(","formatter",")","ax",".","xaxis",".","set_tick_params","(","rotation","=","30",",","labelsize","=","10",")","plt",".","tight_layout","(",")","savepath","=","os",".","path",".","join","(","path",",","key",".","replace","(","\"\/\"",",","\"_\"",")",".","lower","(",")","+","\".png\"",")","plt",".","savefig","(","savepath",",","dpi","=","300",")","plt",".","close","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/util\/log_analyzer.py#L61-L113"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"util\/log_analyzer.py","language":"python","identifier":"_analyze","parameters":"(logs, ds_name)","argument_list":"","return_statement":"","docstring":"Parse and plot receiver metrics","docstring_summary":"Parse and plot receiver metrics","docstring_tokens":["Parse","and","plot","receiver","metrics"],"function":"def _analyze(logs, ds_name):\n \"\"\"Parse and plot receiver metrics\"\"\"\n start_time = _get_time(logs[0])\n ds = list()\n for log in logs:\n logger.debug(log)\n res = _parse(log, start_time)\n logger.debug(res)\n if (res is not None):\n ds.append(res)\n _plot(ds, ds_name)","function_tokens":["def","_analyze","(","logs",",","ds_name",")",":","start_time","=","_get_time","(","logs","[","0","]",")","ds","=","list","(",")","for","log","in","logs",":","logger",".","debug","(","log",")","res","=","_parse","(","log",",","start_time",")","logger",".","debug","(","res",")","if","(","res","is","not","None",")",":","ds",".","append","(","res",")","_plot","(","ds",",","ds_name",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/util\/log_analyzer.py#L116-L126"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"doc\/pandoc.py","language":"python","identifier":"convert_footnotes","parameters":"(text, doc)","argument_list":"","return_statement":"return \"\\n\".join(lines)","docstring":"Convert footnotes from github-flavored markdown into extended markdown\n\n The extended markdown format provides a more specific syntax for footnotes,\n which pandoc can process and convert into LaTeX footnotes.\n\n This function assumes each document has a unique set of footnotes, and that\n multiple docs can adopt the same footnote numbering. It keeps a global\n record of footnotes and increases the footnote number such that the\n concatenated text does not have duplicate footnotes.","docstring_summary":"Convert footnotes from github-flavored markdown into extended markdown","docstring_tokens":["Convert","footnotes","from","github","-","flavored","markdown","into","extended","markdown"],"function":"def convert_footnotes(text, doc):\n \"\"\"Convert footnotes from github-flavored markdown into extended markdown\n\n The extended markdown format provides a more specific syntax for footnotes,\n which pandoc can process and convert into LaTeX footnotes.\n\n This function assumes each document has a unique set of footnotes, and that\n multiple docs can adopt the same footnote numbering. It keeps a global\n record of footnotes and increases the footnote number such that the\n concatenated text does not have duplicate footnotes.\n\n \"\"\"\n lines = text.splitlines()\n footnote = None\n\n for i, line in enumerate(lines):\n if \"\" in line:\n footnote = re.search(r\"(.*?)<\/sup>\", line).group(1)\n\n if doc not in footnote_map:\n footnote_map[doc] = {}\n\n # Assign a global footnote number\n if footnote in footnote_map[doc]:\n i_footnote = footnote_map[doc][footnote]['idx']\n else:\n i_footnote = sum([len(x) for x in footnote_map.values()]) + 1\n footnote_map[doc][footnote] = {\n 'idx': i_footnote,\n 'ref_missing': True\n }\n\n if footnote_map[doc][footnote]['ref_missing']:\n # Footnote reference (without colon)\n lines[i] = line.replace(\"\" + footnote + \"<\/sup>\",\n \"[^{}]\".format(i_footnote))\n footnote_map[doc][footnote]['ref_missing'] = False\n else:\n # Footnote definition (with colon)\n lines[i] = line.replace(\"\" + footnote + \"<\/sup>\",\n \"[^{}]:\".format(i_footnote))\n return \"\\n\".join(lines)","function_tokens":["def","convert_footnotes","(","text",",","doc",")",":","lines","=","text",".","splitlines","(",")","footnote","=","None","for","i",",","line","in","enumerate","(","lines",")",":","if","\"\"","in","line",":","footnote","=","re",".","search","(","r\"(.*?)<\/sup>\"",",","line",")",".","group","(","1",")","if","doc","not","in","footnote_map",":","footnote_map","[","doc","]","=","{","}","# Assign a global footnote number","if","footnote","in","footnote_map","[","doc","]",":","i_footnote","=","footnote_map","[","doc","]","[","footnote","]","[","'idx'","]","else",":","i_footnote","=","sum","(","[","len","(","x",")","for","x","in","footnote_map",".","values","(",")","]",")","+","1","footnote_map","[","doc","]","[","footnote","]","=","{","'idx'",":","i_footnote",",","'ref_missing'",":","True","}","if","footnote_map","[","doc","]","[","footnote","]","[","'ref_missing'","]",":","# Footnote reference (without colon)","lines","[","i","]","=","line",".","replace","(","\"\"","+","footnote","+","\"<\/sup>\"",",","\"[^{}]\"",".","format","(","i_footnote",")",")","footnote_map","[","doc","]","[","footnote","]","[","'ref_missing'","]","=","False","else",":","# Footnote definition (with colon)","lines","[","i","]","=","line",".","replace","(","\"\"","+","footnote","+","\"<\/sup>\"",",","\"[^{}]:\"",".","format","(","i_footnote",")",")","return","\"\\n\"",".","join","(","lines",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/doc\/pandoc.py#L10-L51"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"doc\/pandoc.py","language":"python","identifier":"remove_yaml_front_matter","parameters":"(text)","argument_list":"","return_statement":"return text","docstring":"Remove the YAML front matter of a Markdown document","docstring_summary":"Remove the YAML front matter of a Markdown document","docstring_tokens":["Remove","the","YAML","front","matter","of","a","Markdown","document"],"function":"def remove_yaml_front_matter(text):\n \"\"\"Remove the YAML front matter of a Markdown document\"\"\"\n if text[0:4] == \"---\\n\":\n # Find where the front matter ends\n lines = text.splitlines()\n i_end = 1\n while (i_end < 10): # front matter should use less than 10 lines\n if lines[i_end] == \"---\":\n break\n i_end += 1\n assert (i_end < 10), \"Failed to find YAML front matter closure\"\n\n # Remove also the extra line break after the front matter\n if (lines[i_end + 1] == \"\"):\n i_end += 1\n\n text = \"\\n\".join(lines[(i_end + 1):])\n\n return text","function_tokens":["def","remove_yaml_front_matter","(","text",")",":","if","text","[","0",":","4","]","==","\"---\\n\"",":","# Find where the front matter ends","lines","=","text",".","splitlines","(",")","i_end","=","1","while","(","i_end","<","10",")",":","# front matter should use less than 10 lines","if","lines","[","i_end","]","==","\"---\"",":","break","i_end","+=","1","assert","(","i_end","<","10",")",",","\"Failed to find YAML front matter closure\"","# Remove also the extra line break after the front matter","if","(","lines","[","i_end","+","1","]","==","\"\"",")",":","i_end","+=","1","text","=","\"\\n\"",".","join","(","lines","[","(","i_end","+","1",")",":","]",")","return","text"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/doc\/pandoc.py#L54-L72"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"doc\/pandoc.py","language":"python","identifier":"fix_links","parameters":"(concat_text, docs, title_map, absent_docs)","argument_list":"","return_statement":"return \"\\n\".join(lines)","docstring":"Change document links to anchor links on the concatenated text\n\n The original Markdown docs are linked to each other based on file\n names. However, once they are concatenated, the original file links do not\n work anymore. This function fixes the problem by changing the file links\n into the corresponding in-document anchor links, based on the document's\n title heading.\n\n The other problem is that not all markdown docs are included on the\n compiled pdf version. This function removes links to the docs are not\n present in the concatenated text.","docstring_summary":"Change document links to anchor links on the concatenated text","docstring_tokens":["Change","document","links","to","anchor","links","on","the","concatenated","text"],"function":"def fix_links(concat_text, docs, title_map, absent_docs):\n \"\"\"Change document links to anchor links on the concatenated text\n\n The original Markdown docs are linked to each other based on file\n names. However, once they are concatenated, the original file links do not\n work anymore. This function fixes the problem by changing the file links\n into the corresponding in-document anchor links, based on the document's\n title heading.\n\n The other problem is that not all markdown docs are included on the\n compiled pdf version. This function removes links to the docs are not\n present in the concatenated text.\n\n \"\"\"\n # Replace all document links with the corresponding anchor link\n for doc in docs:\n # Convert title to the corresponding markdown anchor link\n anchor_link = title_map[doc].lower().replace(\" \", \"-\")\n\n # Replace direct links\n original_link = \"({})\".format(doc)\n new_link = \"(#{})\".format(anchor_link)\n concat_text = concat_text.replace(original_link, new_link)\n\n # Fix links pointing to a particular subsection\n concat_text = concat_text.replace(\"({}#\".format(doc), \"(#\")\n\n # Replace links to absent docs\n lines = concat_text.splitlines()\n for doc in absent_docs:\n original_link = \"({})\".format(doc)\n for i, line in enumerate(lines):\n if original_link in line:\n match = re.search(r\"\\[(.*?)\\]\\(\" + doc + r\"\\)\", line)\n lines[i] = line.replace(match.group(0), match.group(1))\n\n return \"\\n\".join(lines)","function_tokens":["def","fix_links","(","concat_text",",","docs",",","title_map",",","absent_docs",")",":","# Replace all document links with the corresponding anchor link","for","doc","in","docs",":","# Convert title to the corresponding markdown anchor link","anchor_link","=","title_map","[","doc","]",".","lower","(",")",".","replace","(","\" \"",",","\"-\"",")","# Replace direct links","original_link","=","\"({})\"",".","format","(","doc",")","new_link","=","\"(#{})\"",".","format","(","anchor_link",")","concat_text","=","concat_text",".","replace","(","original_link",",","new_link",")","# Fix links pointing to a particular subsection","concat_text","=","concat_text",".","replace","(","\"({}#\"",".","format","(","doc",")",",","\"(#\"",")","# Replace links to absent docs","lines","=","concat_text",".","splitlines","(",")","for","doc","in","absent_docs",":","original_link","=","\"({})\"",".","format","(","doc",")","for","i",",","line","in","enumerate","(","lines",")",":","if","original_link","in","line",":","match","=","re",".","search","(","r\"\\[(.*?)\\]\\(\"","+","doc","+","r\"\\)\"",",","line",")","lines","[","i","]","=","line",".","replace","(","match",".","group","(","0",")",",","match",".","group","(","1",")",")","return","\"\\n\"",".","join","(","lines",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/doc\/pandoc.py#L75-L111"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_get_iptables_rules","parameters":"(net_if)","argument_list":"","return_statement":"return rules","docstring":"Get iptables rules that are specifically applied to a target interface\n\n Args:\n net_if : network interface name\n\n Returns:\n list of dictionaries with information of the individual matched rules","docstring_summary":"Get iptables rules that are specifically applied to a target interface","docstring_tokens":["Get","iptables","rules","that","are","specifically","applied","to","a","target","interface"],"function":"def _get_iptables_rules(net_if):\n \"\"\"Get iptables rules that are specifically applied to a target interface\n\n Args:\n net_if : network interface name\n\n Returns:\n list of dictionaries with information of the individual matched rules\n\n \"\"\"\n # Unfortunately, root privileges are required to read the current firewall\n # rules. Hence, we can't read the current rules without eventually asking\n # the root password in dry-run mode. As a workaround, return an empty list\n # as if the rule was not set yet.\n if (runner.dry):\n return []\n\n # Get rules\n cmd = [\"iptables\", \"-L\", \"-v\", \"--line-numbers\"]\n res = runner.run(cmd, root=True, capture_output=True).stdout\n\n # Parse\n header1 = \"\"\n header2 = \"\"\n rules = list()\n for line in res.splitlines():\n if (\"Chain INPUT\" in line.decode()):\n header1 = line.decode()\n\n if (\"destination\" in line.decode()):\n header2 = line.decode()\n\n if (net_if in line.decode()):\n rules.append({\n 'rule': line.decode().split(),\n 'header1': header1,\n 'header2': header2\n })\n\n return rules","function_tokens":["def","_get_iptables_rules","(","net_if",")",":","# Unfortunately, root privileges are required to read the current firewall","# rules. Hence, we can't read the current rules without eventually asking","# the root password in dry-run mode. As a workaround, return an empty list","# as if the rule was not set yet.","if","(","runner",".","dry",")",":","return","[","]","# Get rules","cmd","=","[","\"iptables\"",",","\"-L\"",",","\"-v\"",",","\"--line-numbers\"","]","res","=","runner",".","run","(","cmd",",","root","=","True",",","capture_output","=","True",")",".","stdout","# Parse","header1","=","\"\"","header2","=","\"\"","rules","=","list","(",")","for","line","in","res",".","splitlines","(",")",":","if","(","\"Chain INPUT\"","in","line",".","decode","(",")",")",":","header1","=","line",".","decode","(",")","if","(","\"destination\"","in","line",".","decode","(",")",")",":","header2","=","line",".","decode","(",")","if","(","net_if","in","line",".","decode","(",")",")",":","rules",".","append","(","{","'rule'",":","line",".","decode","(",")",".","split","(",")",",","'header1'",":","header1",",","'header2'",":","header2","}",")","return","rules"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L11-L50"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_is_iptables_igmp_rule_set","parameters":"(net_if, cmd)","argument_list":"","return_statement":"return False","docstring":"Check if an iptables rule for IGMP is already configured\n\n Args:\n net_if : network interface name\n cmd : list with iptables command\n\n Returns:\n True if rule is already set, False otherwise.","docstring_summary":"Check if an iptables rule for IGMP is already configured","docstring_tokens":["Check","if","an","iptables","rule","for","IGMP","is","already","configured"],"function":"def _is_iptables_igmp_rule_set(net_if, cmd):\n \"\"\"Check if an iptables rule for IGMP is already configured\n\n Args:\n net_if : network interface name\n cmd : list with iptables command\n\n Returns:\n True if rule is already set, False otherwise.\n\n \"\"\"\n assert (cmd[0] != \"sudo\")\n for rule in _get_iptables_rules(net_if):\n if (rule['rule'][3] == \"ACCEPT\" and rule['rule'][6] == cmd[6]\n and rule['rule'][4] == \"igmp\"):\n print(\"\\nFirewall rule for IGMP already configured\\n\")\n print(rule['header1'])\n print(rule['header2'])\n print(\" \".join(rule['rule']))\n print(\"\\nSkipping...\")\n return True\n\n return False","function_tokens":["def","_is_iptables_igmp_rule_set","(","net_if",",","cmd",")",":","assert","(","cmd","[","0","]","!=","\"sudo\"",")","for","rule","in","_get_iptables_rules","(","net_if",")",":","if","(","rule","[","'rule'","]","[","3","]","==","\"ACCEPT\"","and","rule","[","'rule'","]","[","6","]","==","cmd","[","6","]","and","rule","[","'rule'","]","[","4","]","==","\"igmp\"",")",":","print","(","\"\\nFirewall rule for IGMP already configured\\n\"",")","print","(","rule","[","'header1'","]",")","print","(","rule","[","'header2'","]",")","print","(","\" \"",".","join","(","rule","[","'rule'","]",")",")","print","(","\"\\nSkipping...\"",")","return","True","return","False"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L53-L75"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_is_iptables_udp_rule_set","parameters":"(net_if, cmd)","argument_list":"","return_statement":"return False","docstring":"Check if an iptables rule for UDP is already configured\n\n Args:\n net_if : network interface name\n cmd : list with iptables command\n\n Returns:\n True if rule is already set, False otherwise.","docstring_summary":"Check if an iptables rule for UDP is already configured","docstring_tokens":["Check","if","an","iptables","rule","for","UDP","is","already","configured"],"function":"def _is_iptables_udp_rule_set(net_if, cmd):\n \"\"\"Check if an iptables rule for UDP is already configured\n\n Args:\n net_if : network interface name\n cmd : list with iptables command\n\n Returns:\n True if rule is already set, False otherwise.\n\n \"\"\"\n assert (cmd[0] != \"sudo\")\n for rule in _get_iptables_rules(net_if):\n if (rule['rule'][3] == \"ACCEPT\" and rule['rule'][6] == cmd[6]\n and rule['rule'][4] == \"udp\" and rule['rule'][12] == cmd[10]):\n print(\"\\nFirewall rule already configured\\n\")\n print(rule['header1'])\n print(rule['header2'])\n print(\" \".join(rule['rule']))\n print(\"\\nSkipping...\")\n return True\n\n return False","function_tokens":["def","_is_iptables_udp_rule_set","(","net_if",",","cmd",")",":","assert","(","cmd","[","0","]","!=","\"sudo\"",")","for","rule","in","_get_iptables_rules","(","net_if",")",":","if","(","rule","[","'rule'","]","[","3","]","==","\"ACCEPT\"","and","rule","[","'rule'","]","[","6","]","==","cmd","[","6","]","and","rule","[","'rule'","]","[","4","]","==","\"udp\"","and","rule","[","'rule'","]","[","12","]","==","cmd","[","10","]",")",":","print","(","\"\\nFirewall rule already configured\\n\"",")","print","(","rule","[","'header1'","]",")","print","(","rule","[","'header2'","]",")","print","(","\" \"",".","join","(","rule","[","'rule'","]",")",")","print","(","\"\\nSkipping...\"",")","return","True","return","False"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L78-L100"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_add_iptables_rule","parameters":"(net_if, cmd)","argument_list":"","return_statement":"","docstring":"Add iptables rule\n\n Args:\n net_if : network interface name\n cmd : list with iptables command","docstring_summary":"Add iptables rule","docstring_tokens":["Add","iptables","rule"],"function":"def _add_iptables_rule(net_if, cmd):\n \"\"\"Add iptables rule\n\n Args:\n net_if : network interface name\n cmd : list with iptables command\n\n \"\"\"\n assert (cmd[0] != \"sudo\")\n\n # Set up the iptables rules\n runner.run(cmd, root=True)\n\n for rule in _get_iptables_rules(net_if):\n print_rule = False\n\n if (rule['rule'][3] == \"ACCEPT\" and rule['rule'][6] == cmd[6]\n and rule['rule'][4] == cmd[4]):\n if (cmd[4] == \"igmp\"):\n print_rule = True\n elif (cmd[4] == \"udp\" and rule['rule'][12] == cmd[10]):\n print_rule = True\n\n if (print_rule):\n print(\"Added iptables rule:\\n\")\n print(rule['header1'])\n print(rule['header2'])\n print(\" \".join(rule['rule']) + \"\\n\")","function_tokens":["def","_add_iptables_rule","(","net_if",",","cmd",")",":","assert","(","cmd","[","0","]","!=","\"sudo\"",")","# Set up the iptables rules","runner",".","run","(","cmd",",","root","=","True",")","for","rule","in","_get_iptables_rules","(","net_if",")",":","print_rule","=","False","if","(","rule","[","'rule'","]","[","3","]","==","\"ACCEPT\"","and","rule","[","'rule'","]","[","6","]","==","cmd","[","6","]","and","rule","[","'rule'","]","[","4","]","==","cmd","[","4","]",")",":","if","(","cmd","[","4","]","==","\"igmp\"",")",":","print_rule","=","True","elif","(","cmd","[","4","]","==","\"udp\"","and","rule","[","'rule'","]","[","12","]","==","cmd","[","10","]",")",":","print_rule","=","True","if","(","print_rule",")",":","print","(","\"Added iptables rule:\\n\"",")","print","(","rule","[","'header1'","]",")","print","(","rule","[","'header2'","]",")","print","(","\" \"",".","join","(","rule","[","'rule'","]",")","+","\"\\n\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L103-L130"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_configure_iptables","parameters":"(net_if, ports, igmp=False, prompt=True)","argument_list":"","return_statement":"","docstring":"Configure iptables rules to accept blocksat traffic on a DVB-S2 interface\n\n Args:\n net_if : DVB network interface name\n ports : ports used for blocks traffic and API traffic\n igmp : Whether or not to configure rule to accept IGMP queries\n prompt : Ask yes\/no before applying any changes","docstring_summary":"Configure iptables rules to accept blocksat traffic on a DVB-S2 interface","docstring_tokens":["Configure","iptables","rules","to","accept","blocksat","traffic","on","a","DVB","-","S2","interface"],"function":"def _configure_iptables(net_if, ports, igmp=False, prompt=True):\n \"\"\"Configure iptables rules to accept blocksat traffic on a DVB-S2 interface\n\n Args:\n net_if : DVB network interface name\n ports : ports used for blocks traffic and API traffic\n igmp : Whether or not to configure rule to accept IGMP queries\n prompt : Ask yes\/no before applying any changes\n\n \"\"\"\n\n cmd = [\n \"iptables\",\n \"-I\",\n \"INPUT\",\n \"-p\",\n \"udp\",\n \"-i\",\n net_if,\n \"--match\",\n \"multiport\",\n \"--dports\",\n \",\".join(ports),\n \"-j\",\n \"ACCEPT\",\n ]\n\n util.fill_print(\n \"A firewall rule is required to accept Blocksat traffic arriving \" +\n \"through interface {} towards UDP ports {}.\".format(\n net_if, \",\".join(ports)))\n\n if (runner.dry):\n util.fill_print(\"The following command would be executed:\")\n\n if (not _is_iptables_udp_rule_set(net_if, cmd)):\n if (runner.dry or (not prompt) or util.ask_yes_or_no(\n \"Add the corresponding ACCEPT firewall rule?\")):\n _add_iptables_rule(net_if, cmd)\n else:\n print(\"\\nFirewall configuration cancelled\")\n\n # We're done, unless we also need to configure an IGMP rule\n if (not igmp):\n return\n\n # IGMP rule supports standalone DVB receivers. The host in this case will\n # need to periodically send IGMP membership reports in order for upstream\n # switches between itself and the DVB receiver to continue delivering the\n # multicast-addressed traffic. This overcomes the scenario where group\n # membership timeouts are implemented by the intermediate switches.\n cmd = [\n \"iptables\",\n \"-I\",\n \"INPUT\",\n \"-p\",\n \"igmp\",\n \"-i\",\n net_if,\n \"-j\",\n \"ACCEPT\",\n ]\n\n print()\n util.fill_print(\n \"A firewall rule is required to accept IGMP queries arriving from the \"\n \"standalone DVB-S2 receiver on interface {}.\".format(net_if))\n\n if (runner.dry):\n util.fill_print(\"The following command would be executed:\")\n\n if (not _is_iptables_igmp_rule_set(net_if, cmd)):\n if (runner.dry or (not prompt) or util.ask_yes_or_no(\n \"Add the corresponding ACCEPT firewall rule?\")):\n _add_iptables_rule(net_if, cmd)\n else:\n print(\"\\nIGMP firewall rule cancelled\")","function_tokens":["def","_configure_iptables","(","net_if",",","ports",",","igmp","=","False",",","prompt","=","True",")",":","cmd","=","[","\"iptables\"",",","\"-I\"",",","\"INPUT\"",",","\"-p\"",",","\"udp\"",",","\"-i\"",",","net_if",",","\"--match\"",",","\"multiport\"",",","\"--dports\"",",","\",\"",".","join","(","ports",")",",","\"-j\"",",","\"ACCEPT\"",",","]","util",".","fill_print","(","\"A firewall rule is required to accept Blocksat traffic arriving \"","+","\"through interface {} towards UDP ports {}.\"",".","format","(","net_if",",","\",\"",".","join","(","ports",")",")",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"The following command would be executed:\"",")","if","(","not","_is_iptables_udp_rule_set","(","net_if",",","cmd",")",")",":","if","(","runner",".","dry","or","(","not","prompt",")","or","util",".","ask_yes_or_no","(","\"Add the corresponding ACCEPT firewall rule?\"",")",")",":","_add_iptables_rule","(","net_if",",","cmd",")","else",":","print","(","\"\\nFirewall configuration cancelled\"",")","# We're done, unless we also need to configure an IGMP rule","if","(","not","igmp",")",":","return","# IGMP rule supports standalone DVB receivers. The host in this case will","# need to periodically send IGMP membership reports in order for upstream","# switches between itself and the DVB receiver to continue delivering the","# multicast-addressed traffic. This overcomes the scenario where group","# membership timeouts are implemented by the intermediate switches.","cmd","=","[","\"iptables\"",",","\"-I\"",",","\"INPUT\"",",","\"-p\"",",","\"igmp\"",",","\"-i\"",",","net_if",",","\"-j\"",",","\"ACCEPT\"",",","]","print","(",")","util",".","fill_print","(","\"A firewall rule is required to accept IGMP queries arriving from the \"","\"standalone DVB-S2 receiver on interface {}.\"",".","format","(","net_if",")",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"The following command would be executed:\"",")","if","(","not","_is_iptables_igmp_rule_set","(","net_if",",","cmd",")",")",":","if","(","runner",".","dry","or","(","not","prompt",")","or","util",".","ask_yes_or_no","(","\"Add the corresponding ACCEPT firewall rule?\"",")",")",":","_add_iptables_rule","(","net_if",",","cmd",")","else",":","print","(","\"\\nIGMP firewall rule cancelled\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L133-L209"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"is_firewalld","parameters":"()","argument_list":"","return_statement":"return (res1.returncode == 0)","docstring":"Check if the firewall is based on firewalld","docstring_summary":"Check if the firewall is based on firewalld","docstring_tokens":["Check","if","the","firewall","is","based","on","firewalld"],"function":"def is_firewalld():\n \"\"\"Check if the firewall is based on firewalld\"\"\"\n if (which('firewall-cmd') is None):\n return False\n\n if (which('systemctl') is None):\n # Can't check whether firewalld is running\n return False\n\n # Run the following commands even in dry-run mode\n res1 = runner.run(['systemctl', 'is-active', '--quiet', 'firewalld'],\n nodry=True,\n nocheck=True)\n res2 = runner.run(['systemctl', 'is-active', '--quiet', 'iptables'],\n nodry=True,\n nocheck=True)\n\n # If running (active), 'is-active' returns 0\n if (res1.returncode == 0 and res2.returncode == 0):\n raise ValueError(\n \"Failed to detect firewall system (firewalld or iptables)\")\n\n return (res1.returncode == 0)","function_tokens":["def","is_firewalld","(",")",":","if","(","which","(","'firewall-cmd'",")","is","None",")",":","return","False","if","(","which","(","'systemctl'",")","is","None",")",":","# Can't check whether firewalld is running","return","False","# Run the following commands even in dry-run mode","res1","=","runner",".","run","(","[","'systemctl'",",","'is-active'",",","'--quiet'",",","'firewalld'","]",",","nodry","=","True",",","nocheck","=","True",")","res2","=","runner",".","run","(","[","'systemctl'",",","'is-active'",",","'--quiet'",",","'iptables'","]",",","nodry","=","True",",","nocheck","=","True",")","# If running (active), 'is-active' returns 0","if","(","res1",".","returncode","==","0","and","res2",".","returncode","==","0",")",":","raise","ValueError","(","\"Failed to detect firewall system (firewalld or iptables)\"",")","return","(","res1",".","returncode","==","0",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L212-L234"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"_configure_firewalld","parameters":"(net_if, ports, src_ip, igmp, prompt)","argument_list":"","return_statement":"","docstring":"Configure firewalld for blocksat and IGMP traffic\n\n Add one rich rule for blocksat traffic coming specifically from the\n satellite of choice (corresponding to the given source IP) and another rich\n rule (if necessary) for IGMP traffic.\n\n NOTE: unlike the iptables configuration, the current firewalld\n configuration disregards the network interface. The alternative to consider\n the interface is to use firewalld zones. However, because the network\n interface may not be dedicated to DVB-S2 traffic (e.g., when using a\n standalone receiver), it can be undesirable to assign the interface\n receiving satellite traffic to a dedicated zone just for blocksat. In\n contrast, the rich rule approach is more generic and works for all types of\n receivers.","docstring_summary":"Configure firewalld for blocksat and IGMP traffic","docstring_tokens":["Configure","firewalld","for","blocksat","and","IGMP","traffic"],"function":"def _configure_firewalld(net_if, ports, src_ip, igmp, prompt):\n \"\"\"Configure firewalld for blocksat and IGMP traffic\n\n Add one rich rule for blocksat traffic coming specifically from the\n satellite of choice (corresponding to the given source IP) and another rich\n rule (if necessary) for IGMP traffic.\n\n NOTE: unlike the iptables configuration, the current firewalld\n configuration disregards the network interface. The alternative to consider\n the interface is to use firewalld zones. However, because the network\n interface may not be dedicated to DVB-S2 traffic (e.g., when using a\n standalone receiver), it can be undesirable to assign the interface\n receiving satellite traffic to a dedicated zone just for blocksat. In\n contrast, the rich rule approach is more generic and works for all types of\n receivers.\n\n \"\"\"\n\n if len(ports) > 1:\n portrange = \"{}-{}\".format(min(ports), max(ports))\n else:\n portrange = ports\n\n util.fill_print(\n \"- Configure the firewall to accept Blocksat traffic arriving \" +\n \"from {} towards address {} on UDP ports {}:\\n\".format(\n src_ip, defs.mcast_ip, portrange))\n\n if (not runner.dry and prompt):\n if (not util.ask_yes_or_no(\"Add firewalld rule?\")):\n print(\"\\nFirewall configuration cancelled\")\n return\n\n rich_rule = (\"rule \"\n \"family=ipv4 \"\n \"source address={} \"\n \"destination address={}\/32 \"\n \"port port={} protocol=udp accept\".format(\n src_ip, defs.mcast_ip, portrange))\n runner.run(['firewall-cmd', '--add-rich-rule', \"{}\".format(rich_rule)],\n root=True)\n\n if (runner.dry):\n print()\n util.fill_print(\n \"NOTE: Add \\\"--permanent\\\" to make it persistent. In this case, \"\n \"remember to reload firewalld afterwards.\")\n\n # We're done, unless we also need to configure an IGMP rule\n if (not igmp):\n return\n\n util.fill_print(\n \"- Allow IGMP packets. This is necessary when using a standalone \"\n \"DVB-S2 receiver connected through a switch:\\n\")\n\n if (not runner.dry and prompt):\n if (not util.ask_yes_or_no(\"Enable IGMP on the firewall?\")):\n print(\"\\nFirewall configuration cancelled\")\n return\n\n runner.run(['firewall-cmd', '--add-protocol=igmp'], root=True)\n print()","function_tokens":["def","_configure_firewalld","(","net_if",",","ports",",","src_ip",",","igmp",",","prompt",")",":","if","len","(","ports",")",">","1",":","portrange","=","\"{}-{}\"",".","format","(","min","(","ports",")",",","max","(","ports",")",")","else",":","portrange","=","ports","util",".","fill_print","(","\"- Configure the firewall to accept Blocksat traffic arriving \"","+","\"from {} towards address {} on UDP ports {}:\\n\"",".","format","(","src_ip",",","defs",".","mcast_ip",",","portrange",")",")","if","(","not","runner",".","dry","and","prompt",")",":","if","(","not","util",".","ask_yes_or_no","(","\"Add firewalld rule?\"",")",")",":","print","(","\"\\nFirewall configuration cancelled\"",")","return","rich_rule","=","(","\"rule \"","\"family=ipv4 \"","\"source address={} \"","\"destination address={}\/32 \"","\"port port={} protocol=udp accept\"",".","format","(","src_ip",",","defs",".","mcast_ip",",","portrange",")",")","runner",".","run","(","[","'firewall-cmd'",",","'--add-rich-rule'",",","\"{}\"",".","format","(","rich_rule",")","]",",","root","=","True",")","if","(","runner",".","dry",")",":","print","(",")","util",".","fill_print","(","\"NOTE: Add \\\"--permanent\\\" to make it persistent. In this case, \"","\"remember to reload firewalld afterwards.\"",")","# We're done, unless we also need to configure an IGMP rule","if","(","not","igmp",")",":","return","util",".","fill_print","(","\"- Allow IGMP packets. This is necessary when using a standalone \"","\"DVB-S2 receiver connected through a switch:\\n\"",")","if","(","not","runner",".","dry","and","prompt",")",":","if","(","not","util",".","ask_yes_or_no","(","\"Enable IGMP on the firewall?\"",")",")",":","print","(","\"\\nFirewall configuration cancelled\"",")","return","runner",".","run","(","[","'firewall-cmd'",",","'--add-protocol=igmp'","]",",","root","=","True",")","print","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L237-L299"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"configure","parameters":"(net_ifs, ports, src_ip, igmp=False, prompt=True, dry=False)","argument_list":"","return_statement":"","docstring":"Configure firewallrules to accept blocksat traffic via DVB interface\n\n Args:\n net_ifs : List of DVB network interface names\n ports : UDP ports used by satellite traffic\n src_ip : Source IP to whitelist (unique to each satellite)\n igmp : Whether or not to configure rule to accept IGMP queries\n prompt : Prompt user to accept configurations before executing them\n dry : Dry run mode","docstring_summary":"Configure firewallrules to accept blocksat traffic via DVB interface","docstring_tokens":["Configure","firewallrules","to","accept","blocksat","traffic","via","DVB","interface"],"function":"def configure(net_ifs, ports, src_ip, igmp=False, prompt=True, dry=False):\n \"\"\"Configure firewallrules to accept blocksat traffic via DVB interface\n\n Args:\n net_ifs : List of DVB network interface names\n ports : UDP ports used by satellite traffic\n src_ip : Source IP to whitelist (unique to each satellite)\n igmp : Whether or not to configure rule to accept IGMP queries\n prompt : Prompt user to accept configurations before executing them\n dry : Dry run mode\n\n \"\"\"\n assert (isinstance(net_ifs, list))\n runner.set_dry(dry)\n util.print_header(\"Firewall Rules\")\n\n for i, net_if in enumerate(net_ifs):\n if (is_firewalld()):\n _configure_firewalld(net_if, ports, src_ip, igmp, prompt)\n else:\n _configure_iptables(net_if, ports, igmp, prompt)\n\n if (i < len(net_ifs) - 1):\n print(\"\")","function_tokens":["def","configure","(","net_ifs",",","ports",",","src_ip",",","igmp","=","False",",","prompt","=","True",",","dry","=","False",")",":","assert","(","isinstance","(","net_ifs",",","list",")",")","runner",".","set_dry","(","dry",")","util",".","print_header","(","\"Firewall Rules\"",")","for","i",",","net_if","in","enumerate","(","net_ifs",")",":","if","(","is_firewalld","(",")",")",":","_configure_firewalld","(","net_if",",","ports",",","src_ip",",","igmp",",","prompt",")","else",":","_configure_iptables","(","net_if",",","ports",",","igmp",",","prompt",")","if","(","i","<","len","(","net_ifs",")","-","1",")",":","print","(","\"\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L302-L325"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Parser for firewall command","docstring_summary":"Parser for firewall command","docstring_tokens":["Parser","for","firewall","command"],"function":"def subparser(subparsers):\n \"\"\"Parser for firewall command\"\"\"\n p = subparsers.add_parser('firewall',\n description=\"Set firewall rules\",\n help='Set firewall rules',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.add_argument('-i',\n '--interface',\n required=True,\n help='Network interface')\n p.add_argument(\n '--standalone',\n default=False,\n action='store_true',\n help='Apply configurations for a standalone DVB-S2 receiver')\n p.add_argument('-y',\n '--yes',\n default=False,\n action='store_true',\n help=\"Default to answering Yes to configuration prompts\")\n p.add_argument(\"--dry-run\",\n action='store_true',\n default=False,\n help=\"Print all commands but do not execute them\")\n p.set_defaults(func=firewall_subcommand)\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'firewall'",",","description","=","\"Set firewall rules\"",",","help","=","'Set firewall rules'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","add_argument","(","'-i'",",","'--interface'",",","required","=","True",",","help","=","'Network interface'",")","p",".","add_argument","(","'--standalone'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Apply configurations for a standalone DVB-S2 receiver'",")","p",".","add_argument","(","'-y'",",","'--yes'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Default to answering Yes to configuration prompts\"",")","p",".","add_argument","(","\"--dry-run\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Print all commands but do not execute them\"",")","p",".","set_defaults","(","func","=","firewall_subcommand",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L328-L353"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/firewall.py","language":"python","identifier":"firewall_subcommand","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Call function that sets firewall rules\n\n Handles the firewall subcommand","docstring_summary":"Call function that sets firewall rules","docstring_tokens":["Call","function","that","sets","firewall","rules"],"function":"def firewall_subcommand(args):\n \"\"\"Call function that sets firewall rules\n\n Handles the firewall subcommand\n\n \"\"\"\n user_info = config.read_cfg_file(args.cfg, args.cfg_dir)\n\n if (user_info is None):\n return\n\n configure([args.interface],\n defs.src_ports,\n user_info['sat']['ip'],\n igmp=args.standalone,\n prompt=(not args.yes),\n dry=args.dry_run)","function_tokens":["def","firewall_subcommand","(","args",")",":","user_info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","user_info","is","None",")",":","return","configure","(","[","args",".","interface","]",",","defs",".","src_ports",",","user_info","[","'sat'","]","[","'ip'","]",",","igmp","=","args",".","standalone",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/firewall.py#L356-L372"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"_check_pip_updates","parameters":"(cfg_dir, cli_version)","argument_list":"","return_statement":"","docstring":"Check if the CLI has updates available via pip\n\n Args:\n cfg_dir : Directory where the .update is located\/created\n cli_version : Current version of the CLI","docstring_summary":"Check if the CLI has updates available via pip","docstring_tokens":["Check","if","the","CLI","has","updates","available","via","pip"],"function":"def _check_pip_updates(cfg_dir, cli_version):\n \"\"\"Check if the CLI has updates available via pip\n\n Args:\n cfg_dir : Directory where the .update is located\/created\n cli_version : Current version of the CLI\n\n \"\"\"\n logger.debug(\"Checking blocksat-cli updates\")\n\n # Save the new pip verification timestamp on the cache file\n update_cache = UpdateCache(cfg_dir)\n update_cache.save()\n\n # Is blocksat-cli installed?\n res = subprocess.run([\"pip3\", \"show\", \"blocksat-cli\"],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL)\n found = (res.returncode == 0)\n\n # If the CLI was not installed via pip, don't check updates\n if (not found):\n logger.debug(\"Could not find blocksat-cli installed via pip3\")\n return\n\n # Is the CLI outdated?\n try:\n outdated_list = json.loads(\n subprocess.check_output(\n [\"pip3\", \"list\", \"--outdated\", \"--format\", \"json\"],\n stderr=subprocess.DEVNULL).decode())\n except subprocess.CalledProcessError:\n # Don't break if the command fails. It could be a problem on pip. For\n # example, there is a bug in which pip throws a TypeError on the \"list\n # --outdated\" command saying: '>' not supported between instances of\n # 'Version' and 'Version'\n logger.warning(\"Failed to check blocksat-cli updates.\")\n return\n\n cli_outdated = False\n for package in outdated_list:\n if (package['name'] == \"blocksat-cli\"):\n cli_outdated = True\n # Save the available update on the cache file\n update_cache.save((package['version'], package['latest_version']))\n logger.debug(\"Update available for blocksat-cli\")\n\n if (not cli_outdated):\n logger.debug(\"blocksat-cli is up-to-date\")\n # Clear a potential update flag on the cache file\n update_cache.save()","function_tokens":["def","_check_pip_updates","(","cfg_dir",",","cli_version",")",":","logger",".","debug","(","\"Checking blocksat-cli updates\"",")","# Save the new pip verification timestamp on the cache file","update_cache","=","UpdateCache","(","cfg_dir",")","update_cache",".","save","(",")","# Is blocksat-cli installed?","res","=","subprocess",".","run","(","[","\"pip3\"",",","\"show\"",",","\"blocksat-cli\"","]",",","stdout","=","subprocess",".","DEVNULL",",","stderr","=","subprocess",".","DEVNULL",")","found","=","(","res",".","returncode","==","0",")","# If the CLI was not installed via pip, don't check updates","if","(","not","found",")",":","logger",".","debug","(","\"Could not find blocksat-cli installed via pip3\"",")","return","# Is the CLI outdated?","try",":","outdated_list","=","json",".","loads","(","subprocess",".","check_output","(","[","\"pip3\"",",","\"list\"",",","\"--outdated\"",",","\"--format\"",",","\"json\"","]",",","stderr","=","subprocess",".","DEVNULL",")",".","decode","(",")",")","except","subprocess",".","CalledProcessError",":","# Don't break if the command fails. It could be a problem on pip. For","# example, there is a bug in which pip throws a TypeError on the \"list","# --outdated\" command saying: '>' not supported between instances of","# 'Version' and 'Version'","logger",".","warning","(","\"Failed to check blocksat-cli updates.\"",")","return","cli_outdated","=","False","for","package","in","outdated_list",":","if","(","package","[","'name'","]","==","\"blocksat-cli\"",")",":","cli_outdated","=","True","# Save the available update on the cache file","update_cache",".","save","(","(","package","[","'version'","]",",","package","[","'latest_version'","]",")",")","logger",".","debug","(","\"Update available for blocksat-cli\"",")","if","(","not","cli_outdated",")",":","logger",".","debug","(","\"blocksat-cli is up-to-date\"",")","# Clear a potential update flag on the cache file","update_cache",".","save","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L73-L123"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"check_cli_updates","parameters":"(args, cli_version)","argument_list":"","return_statement":"","docstring":"Check if the CLI has updates available\n\n Check the cache file first. If the cache is old enough, check updates\n through the pip interface. The cache file can be verified very quickly,\n whereas the verification through pip can be rather slow.\n\n Args:\n args : Arguments from parent argument parser\n cli_version : Current version of the CLI","docstring_summary":"Check if the CLI has updates available","docstring_tokens":["Check","if","the","CLI","has","updates","available"],"function":"def check_cli_updates(args, cli_version):\n \"\"\"Check if the CLI has updates available\n\n Check the cache file first. If the cache is old enough, check updates\n through the pip interface. The cache file can be verified very quickly,\n whereas the verification through pip can be rather slow.\n\n Args:\n args : Arguments from parent argument parser\n cli_version : Current version of the CLI\n\n \"\"\"\n\n # If pip is not available, assume the CLI was not installed via pip\n if (not which(\"pip3\")):\n logger.debug(\"pip3 unavailable\")\n return\n\n # Create the configuration directory if it does not exist\n if not os.path.exists(args.cfg_dir):\n os.makedirs(args.cfg_dir, exist_ok=True)\n\n # Check the update cache file first\n update_cache = UpdateCache(args.cfg_dir)\n\n # If the cache file says there is an update available, check whether the\n # current version is already the updated one. If not, recommend the update.\n if (update_cache.has_update()):\n if (update_cache.new_version() > StrictVersion(cli_version)):\n # Not updated yet. Recommend it.\n update_cache.recommend_update()\n else:\n # Already updated. Clear the update flag.\n update_cache.save()\n return\n\n # If the last update verification was still recent (less than a day ago),\n # do not check pip. Avoid the unnecessary spawning of the pip-checking\n # thread.\n if (update_cache.data):\n time_since_last_check = (datetime.now() - update_cache.last_check())\n if (time_since_last_check < timedelta(days=1)):\n logger.debug(\n \"Last update check was less than a day ago: {}\".format(\n str(time_since_last_check)))\n return\n\n # Check pip updates on a thread. This verification can be slow, so it is\n # better not to block.\n t = threading.Thread(target=_check_pip_updates,\n args=(args.cfg_dir, cli_version))\n t.start()","function_tokens":["def","check_cli_updates","(","args",",","cli_version",")",":","# If pip is not available, assume the CLI was not installed via pip","if","(","not","which","(","\"pip3\"",")",")",":","logger",".","debug","(","\"pip3 unavailable\"",")","return","# Create the configuration directory if it does not exist","if","not","os",".","path",".","exists","(","args",".","cfg_dir",")",":","os",".","makedirs","(","args",".","cfg_dir",",","exist_ok","=","True",")","# Check the update cache file first","update_cache","=","UpdateCache","(","args",".","cfg_dir",")","# If the cache file says there is an update available, check whether the","# current version is already the updated one. If not, recommend the update.","if","(","update_cache",".","has_update","(",")",")",":","if","(","update_cache",".","new_version","(",")",">","StrictVersion","(","cli_version",")",")",":","# Not updated yet. Recommend it.","update_cache",".","recommend_update","(",")","else",":","# Already updated. Clear the update flag.","update_cache",".","save","(",")","return","# If the last update verification was still recent (less than a day ago),","# do not check pip. Avoid the unnecessary spawning of the pip-checking","# thread.","if","(","update_cache",".","data",")",":","time_since_last_check","=","(","datetime",".","now","(",")","-","update_cache",".","last_check","(",")",")","if","(","time_since_last_check","<","timedelta","(","days","=","1",")",")",":","logger",".","debug","(","\"Last update check was less than a day ago: {}\"",".","format","(","str","(","time_since_last_check",")",")",")","return","# Check pip updates on a thread. This verification can be slow, so it is","# better not to block.","t","=","threading",".","Thread","(","target","=","_check_pip_updates",",","args","=","(","args",".","cfg_dir",",","cli_version",")",")","t",".","start","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L126-L177"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.__init__","parameters":"(self, cfg_dir)","argument_list":"","return_statement":"","docstring":"UpdateCache constructor\n\n Args:\n cfg_dir : Directory where the .update is located\/created","docstring_summary":"UpdateCache constructor","docstring_tokens":["UpdateCache","constructor"],"function":"def __init__(self, cfg_dir):\n \"\"\"UpdateCache constructor\n\n Args:\n cfg_dir : Directory where the .update is located\/created\n\n \"\"\"\n super().__init__(cfg_dir, filename=\".update\")","function_tokens":["def","__init__","(","self",",","cfg_dir",")",":","super","(",")",".","__init__","(","cfg_dir",",","filename","=","\".update\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L22-L29"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.last_check","parameters":"(self)","argument_list":"","return_statement":"return datetime.strptime(self.data['last_check'],\n '%Y-%m-%d %H:%M:%S.%f')","docstring":"Return the datetime corresponding to the last update verification","docstring_summary":"Return the datetime corresponding to the last update verification","docstring_tokens":["Return","the","datetime","corresponding","to","the","last","update","verification"],"function":"def last_check(self):\n \"\"\"Return the datetime corresponding to the last update verification\"\"\"\n return datetime.strptime(self.data['last_check'],\n '%Y-%m-%d %H:%M:%S.%f')","function_tokens":["def","last_check","(","self",")",":","return","datetime",".","strptime","(","self",".","data","[","'last_check'","]",",","'%Y-%m-%d %H:%M:%S.%f'",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L31-L34"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.save","parameters":"(self, cli_update=None)","argument_list":"","return_statement":"","docstring":"Save information into the update cache file\n\n Args:\n cli_update : Version of a new CLI version available for update,\n if any","docstring_summary":"Save information into the update cache file","docstring_tokens":["Save","information","into","the","update","cache","file"],"function":"def save(self, cli_update=None):\n \"\"\"Save information into the update cache file\n\n Args:\n cli_update : Version of a new CLI version available for update,\n if any\n\n \"\"\"\n self.data['last_check'] = datetime.now().strftime(\n '%Y-%m-%d %H:%M:%S.%f')\n self.data['cli_update'] = cli_update\n super().save()","function_tokens":["def","save","(","self",",","cli_update","=","None",")",":","self",".","data","[","'last_check'","]","=","datetime",".","now","(",")",".","strftime","(","'%Y-%m-%d %H:%M:%S.%f'",")","self",".","data","[","'cli_update'","]","=","cli_update","super","(",")",".","save","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L36-L47"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.has_update","parameters":"(self)","argument_list":"","return_statement":"return 'cli_update' in self.data and \\\n self.data['cli_update'] is not None","docstring":"Returns whether there is an update available for the CLI","docstring_summary":"Returns whether there is an update available for the CLI","docstring_tokens":["Returns","whether","there","is","an","update","available","for","the","CLI"],"function":"def has_update(self):\n \"\"\"Returns whether there is an update available for the CLI\"\"\"\n return 'cli_update' in self.data and \\\n self.data['cli_update'] is not None","function_tokens":["def","has_update","(","self",")",":","return","'cli_update'","in","self",".","data","and","self",".","data","[","'cli_update'","]","is","not","None"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L49-L52"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.new_version","parameters":"(self)","argument_list":"","return_statement":"return StrictVersion(self.data['cli_update'][1])","docstring":"Get the new version available for an update\n\n Note: This method should be called only if there is a new update, as\n confirmed by \"has_update\". Otherwise, it will throw an exception.","docstring_summary":"Get the new version available for an update","docstring_tokens":["Get","the","new","version","available","for","an","update"],"function":"def new_version(self):\n \"\"\"Get the new version available for an update\n\n Note: This method should be called only if there is a new update, as\n confirmed by \"has_update\". Otherwise, it will throw an exception.\n\n \"\"\"\n return StrictVersion(self.data['cli_update'][1])","function_tokens":["def","new_version","(","self",")",":","return","StrictVersion","(","self",".","data","[","'cli_update'","]","[","1","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L54-L61"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/update.py","language":"python","identifier":"UpdateCache.recommend_update","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Print information regarding the recommended update","docstring_summary":"Print information regarding the recommended update","docstring_tokens":["Print","information","regarding","the","recommended","update"],"function":"def recommend_update(self):\n \"\"\"Print information regarding the recommended update\"\"\"\n if (self.data['cli_update'] is None):\n return\n print(\"\\nUpdate available for blocksat-cli\")\n print(\"Current version: {}.\\nLatest version: {}.\".format(\n self.data['cli_update'][0], self.data['cli_update'][1]))\n print(\"Please run:\\n\\n pip3 install blocksat-cli --upgrade\\n\\n\")","function_tokens":["def","recommend_update","(","self",")",":","if","(","self",".","data","[","'cli_update'","]","is","None",")",":","return","print","(","\"\\nUpdate available for blocksat-cli\"",")","print","(","\"Current version: {}.\\nLatest version: {}.\"",".","format","(","self",".","data","[","'cli_update'","]","[","0","]",",","self",".","data","[","'cli_update'","]","[","1","]",")",")","print","(","\"Please run:\\n\\n pip3 install blocksat-cli --upgrade\\n\\n\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/update.py#L63-L70"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/cache.py","language":"python","identifier":"Cache.__init__","parameters":"(self, cfg_dir, filename=\".cache\")","argument_list":"","return_statement":"","docstring":"Cache constructor\n\n Args:\n cfg_dir : Directory where the .update is located\/created","docstring_summary":"Cache constructor","docstring_tokens":["Cache","constructor"],"function":"def __init__(self, cfg_dir, filename=\".cache\"):\n \"\"\"Cache constructor\n\n Args:\n cfg_dir : Directory where the .update is located\/created\n\n \"\"\"\n self.path = os.path.join(cfg_dir, filename)\n self.data = {}\n self.load()","function_tokens":["def","__init__","(","self",",","cfg_dir",",","filename","=","\".cache\"",")",":","self",".","path","=","os",".","path",".","join","(","cfg_dir",",","filename",")","self",".","data","=","{","}","self",".","load","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/cache.py#L12-L21"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/cache.py","language":"python","identifier":"Cache.load","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Load data from the cache file","docstring_summary":"Load data from the cache file","docstring_tokens":["Load","data","from","the","cache","file"],"function":"def load(self):\n \"\"\"Load data from the cache file\"\"\"\n if (not os.path.exists(self.path)):\n return\n\n try:\n with open(self.path, 'r') as fd:\n self.data = json.load(fd)\n except json.decoder.JSONDecodeError:\n return","function_tokens":["def","load","(","self",")",":","if","(","not","os",".","path",".","exists","(","self",".","path",")",")",":","return","try",":","with","open","(","self",".","path",",","'r'",")","as","fd",":","self",".","data","=","json",".","load","(","fd",")","except","json",".","decoder",".","JSONDecodeError",":","return"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/cache.py#L23-L32"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/cache.py","language":"python","identifier":"Cache.save","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Save data into the cache file\n\n Args:\n cli_update : Version of a new CLI version available for update,\n if any","docstring_summary":"Save data into the cache file","docstring_tokens":["Save","data","into","the","cache","file"],"function":"def save(self):\n \"\"\"Save data into the cache file\n\n Args:\n cli_update : Version of a new CLI version available for update,\n if any\n\n \"\"\"\n with open(self.path, 'w') as fd:\n json.dump(self.data, fd)","function_tokens":["def","save","(","self",")",":","with","open","(","self",".","path",",","'w'",")","as","fd",":","json",".","dump","(","self",".","data",",","fd",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/cache.py#L34-L43"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/cache.py","language":"python","identifier":"Cache.get","parameters":"(self, field)","argument_list":"","return_statement":"","docstring":"Get using dot notation","docstring_summary":"Get using dot notation","docstring_tokens":["Get","using","dot","notation"],"function":"def get(self, field):\n \"\"\"Get using dot notation\"\"\"\n nested_keys = field.split('.')\n tmp = self.data\n for i, key in enumerate(nested_keys):\n if key not in tmp:\n return None\n if i == len(nested_keys) - 1:\n return tmp[key]\n tmp = tmp[key]","function_tokens":["def","get","(","self",",","field",")",":","nested_keys","=","field",".","split","(","'.'",")","tmp","=","self",".","data","for","i",",","key","in","enumerate","(","nested_keys",")",":","if","key","not","in","tmp",":","return","None","if","i","==","len","(","nested_keys",")","-","1",":","return","tmp","[","key","]","tmp","=","tmp","[","key","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/cache.py#L45-L54"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/cache.py","language":"python","identifier":"Cache.set","parameters":"(self, field, val, overwrite=True)","argument_list":"","return_statement":"","docstring":"Set using dot notation","docstring_summary":"Set using dot notation","docstring_tokens":["Set","using","dot","notation"],"function":"def set(self, field, val, overwrite=True):\n \"\"\"Set using dot notation\"\"\"\n nested_keys = field.split('.')\n tmp = self.data\n for i, key in enumerate(nested_keys):\n if key not in tmp:\n tmp[key] = {}\n if i == len(nested_keys) - 1:\n if (key in tmp and not overwrite):\n return\n tmp[key] = val\n tmp = tmp[key]","function_tokens":["def","set","(","self",",","field",",","val",",","overwrite","=","True",")",":","nested_keys","=","field",".","split","(","'.'",")","tmp","=","self",".","data","for","i",",","key","in","enumerate","(","nested_keys",")",":","if","key","not","in","tmp",":","tmp","[","key","]","=","{","}","if","i","==","len","(","nested_keys",")","-","1",":","if","(","key","in","tmp","and","not","overwrite",")",":","return","tmp","[","key","]","=","val","tmp","=","tmp","[","key","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/cache.py#L56-L67"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"typed_input","parameters":"(msg, hint=None, in_type=int, default=None)","argument_list":"","return_statement":"return res","docstring":"Ask for user input of a specific type","docstring_summary":"Ask for user input of a specific type","docstring_tokens":["Ask","for","user","input","of","a","specific","type"],"function":"def typed_input(msg, hint=None, in_type=int, default=None):\n \"\"\"Ask for user input of a specific type\"\"\"\n res = None\n while (res is None):\n try:\n if (default is not None):\n assert (isinstance(default, in_type))\n input_val = _input(msg + \": [{}] \".format(default)) or default\n else:\n input_val = _input(msg + \": \")\n res = in_type(input_val)\n except ValueError:\n if (hint is None):\n if (in_type == int):\n print(\"Please enter an integer number\")\n elif (in_type == float):\n print(\"Please enter a number\")\n elif (in_type == IPv4Address):\n print(\"Please enter a valid IPv4 address\")\n else:\n type_str = in_type.__name__\n print(\"Please enter a {}\".format(type_str))\n else:\n print(hint)\n assert (res is not None)\n assert (isinstance(res, in_type))\n return res","function_tokens":["def","typed_input","(","msg",",","hint","=","None",",","in_type","=","int",",","default","=","None",")",":","res","=","None","while","(","res","is","None",")",":","try",":","if","(","default","is","not","None",")",":","assert","(","isinstance","(","default",",","in_type",")",")","input_val","=","_input","(","msg","+","\": [{}] \"",".","format","(","default",")",")","or","default","else",":","input_val","=","_input","(","msg","+","\": \"",")","res","=","in_type","(","input_val",")","except","ValueError",":","if","(","hint","is","None",")",":","if","(","in_type","==","int",")",":","print","(","\"Please enter an integer number\"",")","elif","(","in_type","==","float",")",":","print","(","\"Please enter a number\"",")","elif","(","in_type","==","IPv4Address",")",":","print","(","\"Please enter a valid IPv4 address\"",")","else",":","type_str","=","in_type",".","__name__","print","(","\"Please enter a {}\"",".","format","(","type_str",")",")","else",":","print","(","hint",")","assert","(","res","is","not","None",")","assert","(","isinstance","(","res",",","in_type",")",")","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L26-L52"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"string_input","parameters":"(msg, default=None)","argument_list":"","return_statement":"return res","docstring":"Ask for a non-null string input with an optional default value","docstring_summary":"Ask for a non-null string input with an optional default value","docstring_tokens":["Ask","for","a","non","-","null","string","input","with","an","optional","default","value"],"function":"def string_input(msg, default=None):\n \"\"\"Ask for a non-null string input with an optional default value\"\"\"\n res = \"\"\n while (len(res) == 0):\n if (default is not None):\n assert (isinstance(default, str))\n res = _input(msg + \": [{}] \".format(default)) or default\n else:\n res = _input(msg + \": \")\n return res","function_tokens":["def","string_input","(","msg",",","default","=","None",")",":","res","=","\"\"","while","(","len","(","res",")","==","0",")",":","if","(","default","is","not","None",")",":","assert","(","isinstance","(","default",",","str",")",")","res","=","_input","(","msg","+","\": [{}] \"",".","format","(","default",")",")","or","default","else",":","res","=","_input","(","msg","+","\": \"",")","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L55-L64"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"ask_yes_or_no","parameters":"(msg, default=\"y\", help_msg=None)","argument_list":"","return_statement":"return (response == \"y\")","docstring":"Yes or no question\n\n Args:\n msg : the message or question to ask the user\n default : default response\n help_msg : Optional help message\n\n Returns:\n True if answer is yes, False otherwise.","docstring_summary":"Yes or no question","docstring_tokens":["Yes","or","no","question"],"function":"def ask_yes_or_no(msg, default=\"y\", help_msg=None):\n \"\"\"Yes or no question\n\n Args:\n msg : the message or question to ask the user\n default : default response\n help_msg : Optional help message\n\n Returns:\n True if answer is yes, False otherwise.\n\n \"\"\"\n response = None\n\n if (default == \"y\"):\n options = \"[Y\/n]\"\n else:\n options = \"[N\/y]\"\n\n while response not in {\"y\", \"n\"}:\n if (help_msg is None):\n question = msg + \" \" + options + \" \"\n raw_resp = _input(question) or default\n else:\n print(textwrap.fill(msg))\n print()\n print(textwrap.fill(help_msg))\n print()\n raw_resp = _input(\"Answer \" + options + \" \") or default\n\n response = raw_resp.lower()\n\n if (response not in [\"y\", \"n\"]):\n print(\"Please enter \\\"y\\\" or \\\"n\\\"\")\n\n return (response == \"y\")","function_tokens":["def","ask_yes_or_no","(","msg",",","default","=","\"y\"",",","help_msg","=","None",")",":","response","=","None","if","(","default","==","\"y\"",")",":","options","=","\"[Y\/n]\"","else",":","options","=","\"[N\/y]\"","while","response","not","in","{","\"y\"",",","\"n\"","}",":","if","(","help_msg","is","None",")",":","question","=","msg","+","\" \"","+","options","+","\" \"","raw_resp","=","_input","(","question",")","or","default","else",":","print","(","textwrap",".","fill","(","msg",")",")","print","(",")","print","(","textwrap",".","fill","(","help_msg",")",")","print","(",")","raw_resp","=","_input","(","\"Answer \"","+","options","+","\" \"",")","or","default","response","=","raw_resp",".","lower","(",")","if","(","response","not","in","[","\"y\"",",","\"n\"","]",")",":","print","(","\"Please enter \\\"y\\\" or \\\"n\\\"\"",")","return","(","response","==","\"y\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L67-L102"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"ask_multiple_choice","parameters":"(vec,\n msg,\n label,\n to_str,\n help_msg=None,\n none_option=False,\n none_str=\"None of the above\")","argument_list":"","return_statement":"","docstring":"Multiple choice question\n\n Args:\n vec : Vector with elements to choose from\n msg : Msg to prompt user for choice\n label : Description\/label of what \"vec\" holdes\n to_str : Function that prints information about elements\n help_msg : Optional help message\n none_option : Whether to display a \"none of the above\" option\n none_str : What do display as \"none of the above\" message\n\n Returns:\n Chosen element","docstring_summary":"Multiple choice question","docstring_tokens":["Multiple","choice","question"],"function":"def ask_multiple_choice(vec,\n msg,\n label,\n to_str,\n help_msg=None,\n none_option=False,\n none_str=\"None of the above\"):\n \"\"\"Multiple choice question\n\n Args:\n vec : Vector with elements to choose from\n msg : Msg to prompt user for choice\n label : Description\/label of what \"vec\" holdes\n to_str : Function that prints information about elements\n help_msg : Optional help message\n none_option : Whether to display a \"none of the above\" option\n none_str : What do display as \"none of the above\" message\n\n Returns:\n Chosen element\n\n \"\"\"\n if (none_option):\n assert (len(vec) > 0)\n else:\n assert (len(vec) > 1)\n\n print(msg)\n\n for i_elem, elem in enumerate(vec):\n elem_str = to_str(elem)\n print(\"[%2u] %s\" % (i_elem, elem_str))\n\n if (none_option):\n print(\"[%2u] %s\" % (len(vec), none_str))\n\n if (help_msg is not None):\n print()\n print(help_msg)\n\n resp = None\n while (not isinstance(resp, int)):\n try:\n resp = int(_input(\"\\n%s number: \" % (label)))\n except ValueError:\n print(\"Please choose a number\")\n continue\n\n max_resp = len(vec) + 1 if none_option else len(vec)\n if (resp >= max_resp):\n print(\"Please choose number from 0 to %u\" % (max_resp - 1))\n resp = None\n continue\n\n if (none_option and resp == len(vec)):\n choice = None\n print(none_str)\n else:\n choice = copy.deepcopy(vec[resp])\n # NOTE: deep copy to prevent the caller from changing the original\n # element.\n print(to_str(choice))\n print()\n\n return choice","function_tokens":["def","ask_multiple_choice","(","vec",",","msg",",","label",",","to_str",",","help_msg","=","None",",","none_option","=","False",",","none_str","=","\"None of the above\"",")",":","if","(","none_option",")",":","assert","(","len","(","vec",")",">","0",")","else",":","assert","(","len","(","vec",")",">","1",")","print","(","msg",")","for","i_elem",",","elem","in","enumerate","(","vec",")",":","elem_str","=","to_str","(","elem",")","print","(","\"[%2u] %s\"","%","(","i_elem",",","elem_str",")",")","if","(","none_option",")",":","print","(","\"[%2u] %s\"","%","(","len","(","vec",")",",","none_str",")",")","if","(","help_msg","is","not","None",")",":","print","(",")","print","(","help_msg",")","resp","=","None","while","(","not","isinstance","(","resp",",","int",")",")",":","try",":","resp","=","int","(","_input","(","\"\\n%s number: \"","%","(","label",")",")",")","except","ValueError",":","print","(","\"Please choose a number\"",")","continue","max_resp","=","len","(","vec",")","+","1","if","none_option","else","len","(","vec",")","if","(","resp",">=","max_resp",")",":","print","(","\"Please choose number from 0 to %u\"","%","(","max_resp","-","1",")",")","resp","=","None","continue","if","(","none_option","and","resp","==","len","(","vec",")",")",":","choice","=","None","print","(","none_str",")","else",":","choice","=","copy",".","deepcopy","(","vec","[","resp","]",")","# NOTE: deep copy to prevent the caller from changing the original","# element.","print","(","to_str","(","choice",")",")","print","(",")","return","choice"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L105-L169"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"print_header","parameters":"(header, target_len=80)","argument_list":"","return_statement":"","docstring":"Print section header","docstring_summary":"Print section header","docstring_tokens":["Print","section","header"],"function":"def print_header(header, target_len=80):\n \"\"\"Print section header\"\"\"\n\n prefix = \"\"\n suffix = \"\"\n header_len = len(header) + 2\n remaining = target_len - header_len\n prefix_len = int(remaining \/ 2)\n suffix_len = int(remaining \/ 2)\n\n if (remaining % 1 == 1):\n prefix_len += 1\n\n for i in range(0, prefix_len):\n prefix += \"-\"\n\n for i in range(0, suffix_len):\n suffix += \"-\"\n\n print(\"\\n\" + prefix + \" \" + header + \" \" + suffix)","function_tokens":["def","print_header","(","header",",","target_len","=","80",")",":","prefix","=","\"\"","suffix","=","\"\"","header_len","=","len","(","header",")","+","2","remaining","=","target_len","-","header_len","prefix_len","=","int","(","remaining","\/","2",")","suffix_len","=","int","(","remaining","\/","2",")","if","(","remaining","%","1","==","1",")",":","prefix_len","+=","1","for","i","in","range","(","0",",","prefix_len",")",":","prefix","+=","\"-\"","for","i","in","range","(","0",",","suffix_len",")",":","suffix","+=","\"-\"","print","(","\"\\n\"","+","prefix","+","\" \"","+","header","+","\" \"","+","suffix",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L172-L191"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"print_sub_header","parameters":"(header, target_len=60)","argument_list":"","return_statement":"","docstring":"Print sub-section header","docstring_summary":"Print sub-section header","docstring_tokens":["Print","sub","-","section","header"],"function":"def print_sub_header(header, target_len=60):\n \"\"\"Print sub-section header\"\"\"\n print_header(header, target_len=target_len)","function_tokens":["def","print_sub_header","(","header",",","target_len","=","60",")",":","print_header","(","header",",","target_len","=","target_len",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L194-L196"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"get_home_dir","parameters":"()","argument_list":"","return_statement":"return os.path.expanduser(\"~\" + user)","docstring":"Get the user's home directory even if running with sudo","docstring_summary":"Get the user's home directory even if running with sudo","docstring_tokens":["Get","the","user","s","home","directory","even","if","running","with","sudo"],"function":"def get_home_dir():\n \"\"\"Get the user's home directory even if running with sudo\"\"\"\n sudo_user = os.environ.get('SUDO_USER')\n user = sudo_user if sudo_user is not None else \"\"\n return os.path.expanduser(\"~\" + user)","function_tokens":["def","get_home_dir","(",")",":","sudo_user","=","os",".","environ",".","get","(","'SUDO_USER'",")","user","=","sudo_user","if","sudo_user","is","not","None","else","\"\"","return","os",".","path",".","expanduser","(","\"~\"","+","user",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L206-L210"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"_print_urlretrieve_progress","parameters":"(block_num, block_size, total_size)","argument_list":"","return_statement":"","docstring":"Print progress on urlretrieve's reporthook","docstring_summary":"Print progress on urlretrieve's reporthook","docstring_tokens":["Print","progress","on","urlretrieve","s","reporthook"],"function":"def _print_urlretrieve_progress(block_num, block_size, total_size):\n \"\"\"Print progress on urlretrieve's reporthook\"\"\"\n downloaded = block_num * block_size\n progress = 100 * downloaded \/ total_size\n if (total_size > 0):\n print(\"Download progress: {:4.1f}%\".format(progress), end='\\r')\n if (progress >= 100):\n print(\"\")","function_tokens":["def","_print_urlretrieve_progress","(","block_num",",","block_size",",","total_size",")",":","downloaded","=","block_num","*","block_size","progress","=","100","*","downloaded","\/","total_size","if","(","total_size",">","0",")",":","print","(","\"Download progress: {:4.1f}%\"",".","format","(","progress",")",",","end","=","'\\r'",")","if","(","progress",">=","100",")",":","print","(","\"\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L335-L342"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"download_file","parameters":"(url, destdir, dry_run, logger=None)","argument_list":"","return_statement":"return local_path","docstring":"Download file from a given URL\n\n Args:\n url : Download URL.\n destdir : Destination directory.\n dry_run : Dry-run mode.\n logger : Optional logger to print messages.\n\n Returns:\n Path to downloaded file if the download is successful. None in\n dry-run mode or if the download fails.","docstring_summary":"Download file from a given URL","docstring_tokens":["Download","file","from","a","given","URL"],"function":"def download_file(url, destdir, dry_run, logger=None):\n \"\"\"Download file from a given URL\n\n Args:\n url : Download URL.\n destdir : Destination directory.\n dry_run : Dry-run mode.\n logger : Optional logger to print messages.\n\n Returns:\n Path to downloaded file if the download is successful. None in\n dry-run mode or if the download fails.\n\n \"\"\"\n filename = url.split('\/')[-1]\n local_path = os.path.join(destdir, filename)\n\n if (dry_run):\n print(\"Download: {}\".format(url))\n print(\"Save at: {}\".format(destdir))\n return\n\n if (logger is not None):\n logger.debug(\"Download {} and save at {}\".format(url, destdir))\n\n try:\n urlretrieve(url, local_path, _print_urlretrieve_progress)\n except HTTPError as e:\n logger.error(str(e))\n return\n\n return local_path","function_tokens":["def","download_file","(","url",",","destdir",",","dry_run",",","logger","=","None",")",":","filename","=","url",".","split","(","'\/'",")","[","-","1","]","local_path","=","os",".","path",".","join","(","destdir",",","filename",")","if","(","dry_run",")",":","print","(","\"Download: {}\"",".","format","(","url",")",")","print","(","\"Save at: {}\"",".","format","(","destdir",")",")","return","if","(","logger","is","not","None",")",":","logger",".","debug","(","\"Download {} and save at {}\"",".","format","(","url",",","destdir",")",")","try",":","urlretrieve","(","url",",","local_path",",","_print_urlretrieve_progress",")","except","HTTPError","as","e",":","logger",".","error","(","str","(","e",")",")","return","return","local_path"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L345-L376"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"ProcessRunner._get_cmd_str","parameters":"(self, orig_cmd)","argument_list":"","return_statement":"return \"> \" + \" \".join(quoted_cmd)","docstring":"Generate string for command\n\n If any argument is supposed to be quoted (i.e., has spaces), add the\n quotes.","docstring_summary":"Generate string for command","docstring_tokens":["Generate","string","for","command"],"function":"def _get_cmd_str(self, orig_cmd):\n \"\"\"Generate string for command\n\n If any argument is supposed to be quoted (i.e., has spaces), add the\n quotes.\n\n \"\"\"\n quoted_cmd = orig_cmd.copy()\n for i, elem in enumerate(quoted_cmd):\n if (\" \" in elem):\n quoted_cmd[i] = \"\\'{}\\'\".format(elem)\n return \"> \" + \" \".join(quoted_cmd)","function_tokens":["def","_get_cmd_str","(","self",",","orig_cmd",")",":","quoted_cmd","=","orig_cmd",".","copy","(",")","for","i",",","elem","in","enumerate","(","quoted_cmd",")",":","if","(","\" \"","in","elem",")",":","quoted_cmd","[","i","]","=","\"\\'{}\\'\"",".","format","(","elem",")","return","\"> \"","+","\" \"",".","join","(","quoted_cmd",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L220-L231"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"ProcessRunner.create_file","parameters":"(self, content, path, **kwargs)","argument_list":"","return_statement":"","docstring":"Create file with given content on a specified path\n\n If the target path requires root privileges, this function can be\n executed with option root=True.","docstring_summary":"Create file with given content on a specified path","docstring_tokens":["Create","file","with","given","content","on","a","specified","path"],"function":"def create_file(self, content, path, **kwargs):\n \"\"\"Create file with given content on a specified path\n\n If the target path requires root privileges, this function can be\n executed with option root=True.\n\n \"\"\"\n if (self.dry):\n # In dry-run mode, run an equivalent echo command.\n cmd = [\"echo\", \"-e\", repr(content), \">\", path]\n else:\n tmp_file = tempfile.NamedTemporaryFile(mode=\"w\", delete=False)\n with tmp_file as fd:\n fd.write(content)\n cmd = [\"mv\", tmp_file.name, path]\n self.run(cmd, **kwargs)\n if (not self.dry):\n self.logger.info(\"Created file {}\".format(path))","function_tokens":["def","create_file","(","self",",","content",",","path",",","*","*","kwargs",")",":","if","(","self",".","dry",")",":","# In dry-run mode, run an equivalent echo command.","cmd","=","[","\"echo\"",",","\"-e\"",",","repr","(","content",")",",","\">\"",",","path","]","else",":","tmp_file","=","tempfile",".","NamedTemporaryFile","(","mode","=","\"w\"",",","delete","=","False",")","with","tmp_file","as","fd",":","fd",".","write","(","content",")","cmd","=","[","\"mv\"",",","tmp_file",".","name",",","path","]","self",".","run","(","cmd",",","*","*","kwargs",")","if","(","not","self",".","dry",")",":","self",".","logger",".","info","(","\"Created file {}\"",".","format","(","path",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L284-L301"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"Pipe.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Create unnamed pipe","docstring_summary":"Create unnamed pipe","docstring_tokens":["Create","unnamed","pipe"],"function":"def __init__(self):\n \"\"\"Create unnamed pipe\"\"\"\n r_fd, w_fd = os.pipe()\n\n self.r_fd = r_fd # read file descriptor\n self.r_fo = os.fdopen(r_fd, \"r\") # read file object\n\n self.w_fd = w_fd # write file descriptor\n self.w_fo = os.fdopen(w_fd, \"w\")","function_tokens":["def","__init__","(","self",")",":","r_fd",",","w_fd","=","os",".","pipe","(",")","self",".","r_fd","=","r_fd","# read file descriptor","self",".","r_fo","=","os",".","fdopen","(","r_fd",",","\"r\"",")","# read file object","self",".","w_fd","=","w_fd","# write file descriptor","self",".","w_fo","=","os",".","fdopen","(","w_fd",",","\"w\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L306-L314"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"Pipe.__del__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close pipe","docstring_summary":"Close pipe","docstring_tokens":["Close","pipe"],"function":"def __del__(self):\n \"\"\"Close pipe\"\"\"\n self.r_fo.close()\n self.w_fo.close()","function_tokens":["def","__del__","(","self",")",":","self",".","r_fo",".","close","(",")","self",".","w_fo",".","close","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L316-L319"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"Pipe.readline","parameters":"(self)","argument_list":"","return_statement":"return self.r_fo.readline()","docstring":"Read line from pipe file","docstring_summary":"Read line from pipe file","docstring_tokens":["Read","line","from","pipe","file"],"function":"def readline(self):\n \"\"\"Read line from pipe file\"\"\"\n return self.r_fo.readline()","function_tokens":["def","readline","(","self",")",":","return","self",".","r_fo",".","readline","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L321-L323"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/util.py","language":"python","identifier":"Pipe.write","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Write data to pipe file\n\n Args:\n data : The data to write into the pipe file","docstring_summary":"Write data to pipe file","docstring_tokens":["Write","data","to","pipe","file"],"function":"def write(self, data):\n \"\"\"Write data to pipe file\n\n Args:\n data : The data to write into the pipe file\n\n \"\"\"\n self.w_fo.write(data)","function_tokens":["def","write","(","self",",","data",")",":","self",".","w_fo",".","write","(","data",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/util.py#L325-L332"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/sdr.py","language":"python","identifier":"_tune_max_pipe_size","parameters":"(pipesize)","argument_list":"","return_statement":"","docstring":"Tune the maximum size of pipes","docstring_summary":"Tune the maximum size of pipes","docstring_tokens":["Tune","the","maximum","size","of","pipes"],"function":"def _tune_max_pipe_size(pipesize):\n \"\"\"Tune the maximum size of pipes\"\"\"\n if (not which(\"sysctl\")):\n logging.error(\"Couldn't tune max-pipe-size. Please check how to tune \"\n \"it in your OS.\")\n return False\n\n ret = subprocess.check_output([\"sysctl\", \"fs.pipe-max-size\"])\n current_max = int(ret.decode().split()[-1])\n\n if (current_max < pipesize):\n cmd = [\"sysctl\", \"-w\", \"fs.pipe-max-size=\" + str(pipesize)]\n print(\n textwrap.fill(\"The maximum pipe size that is currently \"\n \"configured in your OS is of {} bytes, which is \"\n \"not sufficient for the receiver application. \"\n \"It will be necessary to run the following command \"\n \"as root:\".format(current_max),\n width=80))\n print(\"\\n\" + \" \".join(cmd) + \"\\n\")\n\n if (not util.ask_yes_or_no(\"Is that OK?\", default=\"y\")):\n print(\"Abort\")\n return False\n\n res = runner.run(cmd, root=True)\n return (res.returncode == 0)\n else:\n return True","function_tokens":["def","_tune_max_pipe_size","(","pipesize",")",":","if","(","not","which","(","\"sysctl\"",")",")",":","logging",".","error","(","\"Couldn't tune max-pipe-size. Please check how to tune \"","\"it in your OS.\"",")","return","False","ret","=","subprocess",".","check_output","(","[","\"sysctl\"",",","\"fs.pipe-max-size\"","]",")","current_max","=","int","(","ret",".","decode","(",")",".","split","(",")","[","-","1","]",")","if","(","current_max","<","pipesize",")",":","cmd","=","[","\"sysctl\"",",","\"-w\"",",","\"fs.pipe-max-size=\"","+","str","(","pipesize",")","]","print","(","textwrap",".","fill","(","\"The maximum pipe size that is currently \"","\"configured in your OS is of {} bytes, which is \"","\"not sufficient for the receiver application. \"","\"It will be necessary to run the following command \"","\"as root:\"",".","format","(","current_max",")",",","width","=","80",")",")","print","(","\"\\n\"","+","\" \"",".","join","(","cmd",")","+","\"\\n\"",")","if","(","not","util",".","ask_yes_or_no","(","\"Is that OK?\"",",","default","=","\"y\"",")",")",":","print","(","\"Abort\"",")","return","False","res","=","runner",".","run","(","cmd",",","root","=","True",")","return","(","res",".","returncode","==","0",")","else",":","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/sdr.py#L15-L43"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/sdr.py","language":"python","identifier":"_get_monitor","parameters":"(args)","argument_list":"","return_statement":"return monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=scrolling,\n echo=echo,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)","docstring":"Create an object of the Monitor class\n\n Args:\n args : SDR parser arguments\n sat_name : Satellite name","docstring_summary":"Create an object of the Monitor class","docstring_tokens":["Create","an","object","of","the","Monitor","class"],"function":"def _get_monitor(args):\n \"\"\"Create an object of the Monitor class\n\n Args:\n args : SDR parser arguments\n sat_name : Satellite name\n\n \"\"\"\n # If debugging leandvb, don't echo the logs to stdout, otherwise the\n # logs get mixed on the console and it becomes hard to read them.\n echo = (args.debug_dvbs2 == 0)\n\n # Force scrolling logs if tsp is configured to print to stdout\n scrolling = tsp.prints_to_stdout(args) or args.log_scrolling\n\n return monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=scrolling,\n echo=echo,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)","function_tokens":["def","_get_monitor","(","args",")",":","# If debugging leandvb, don't echo the logs to stdout, otherwise the","# logs get mixed on the console and it becomes hard to read them.","echo","=","(","args",".","debug_dvbs2","==","0",")","# Force scrolling logs if tsp is configured to print to stdout","scrolling","=","tsp",".","prints_to_stdout","(","args",")","or","args",".","log_scrolling","return","monitoring",".","Monitor","(","args",".","cfg_dir",",","logfile","=","args",".","log_file",",","scroll","=","scrolling",",","echo","=","echo",",","min_interval","=","args",".","log_interval",",","server","=","args",".","monitoring_server",",","port","=","args",".","monitoring_port",",","report","=","args",".","report",",","report_opts","=","monitoring",".","get_report_opts","(","args",")",",","utc","=","args",".","utc",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/sdr.py#L63-L87"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/sdr.py","language":"python","identifier":"_monitor_demod_info","parameters":"(info_pipe, monitor)","argument_list":"","return_statement":"","docstring":"Monitor leandvb's demodulator information\n\n Continuously read the demodulator information printed by leandvb into the\n descriptor pointed by --fd-info, which is tied to an unnamed pipe\n file. Then, feed the information into the monitor object.\n\n Args:\n info_pipe : Pipe object pointing to the pipe file that is used as\n leandvb's --fd-info descriptor\n monitor : Object of the Monitor class used to handle receiver\n monitoring and logging","docstring_summary":"Monitor leandvb's demodulator information","docstring_tokens":["Monitor","leandvb","s","demodulator","information"],"function":"def _monitor_demod_info(info_pipe, monitor):\n \"\"\"Monitor leandvb's demodulator information\n\n Continuously read the demodulator information printed by leandvb into the\n descriptor pointed by --fd-info, which is tied to an unnamed pipe\n file. Then, feed the information into the monitor object.\n\n Args:\n info_pipe : Pipe object pointing to the pipe file that is used as\n leandvb's --fd-info descriptor\n monitor : Object of the Monitor class used to handle receiver\n monitoring and logging\n\n \"\"\"\n assert (isinstance(info_pipe, util.Pipe))\n\n # \"Standard\" status format accepted by the Monitor class\n status = {'lock': (False, None), 'level': None, 'snr': None, 'ber': None}\n\n while True:\n line = info_pipe.readline()\n\n if \"FRAMELOCK\" in line:\n status['lock'] = (line.split()[-1] == \"1\", None)\n\n for metric in rx_stat_map:\n if metric in line:\n val = float(line.split()[-1])\n unit = rx_stat_map[metric]['unit']\n key = rx_stat_map[metric]['key']\n status[key] = (val, unit)\n\n # If unlocked, clear the status metrics that depend on receiver locking\n # (they will show garbage if unlocked). If locked, just make sure that\n # all the required metrics are filled in the status dictionary.\n ready = True\n for metric in rx_stat_map:\n key = rx_stat_map[metric]['key']\n if status['lock'][0]:\n if key not in status or status[key] is None:\n ready = False\n else:\n if (key in status):\n del status[key]\n\n if (not ready):\n continue\n\n monitor.update(status)","function_tokens":["def","_monitor_demod_info","(","info_pipe",",","monitor",")",":","assert","(","isinstance","(","info_pipe",",","util",".","Pipe",")",")","# \"Standard\" status format accepted by the Monitor class","status","=","{","'lock'",":","(","False",",","None",")",",","'level'",":","None",",","'snr'",":","None",",","'ber'",":","None","}","while","True",":","line","=","info_pipe",".","readline","(",")","if","\"FRAMELOCK\"","in","line",":","status","[","'lock'","]","=","(","line",".","split","(",")","[","-","1","]","==","\"1\"",",","None",")","for","metric","in","rx_stat_map",":","if","metric","in","line",":","val","=","float","(","line",".","split","(",")","[","-","1","]",")","unit","=","rx_stat_map","[","metric","]","[","'unit'","]","key","=","rx_stat_map","[","metric","]","[","'key'","]","status","[","key","]","=","(","val",",","unit",")","# If unlocked, clear the status metrics that depend on receiver locking","# (they will show garbage if unlocked). If locked, just make sure that","# all the required metrics are filled in the status dictionary.","ready","=","True","for","metric","in","rx_stat_map",":","key","=","rx_stat_map","[","metric","]","[","'key'","]","if","status","[","'lock'","]","[","0","]",":","if","key","not","in","status","or","status","[","key","]","is","None",":","ready","=","False","else",":","if","(","key","in","status",")",":","del","status","[","key","]","if","(","not","ready",")",":","continue","monitor",".","update","(","status",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/sdr.py#L90-L138"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/sdr.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Parser for sdr command","docstring_summary":"Parser for sdr command","docstring_tokens":["Parser","for","sdr","command"],"function":"def subparser(subparsers):\n \"\"\"Parser for sdr command\"\"\"\n p = subparsers.add_parser('sdr',\n description=\"Launch SDR receiver\",\n help='Launch SDR receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n # Monitoring options\n monitoring.add_to_parser(p)\n\n rtl_p = p.add_argument_group('rtl_sdr options')\n rtl_p.add_argument('--sps',\n default=2.0,\n type=float,\n help='Samples per symbol, or, equivalently, the '\n 'target oversampling ratio')\n rtl_p.add_argument('--rtl-idx',\n default=0,\n type=int,\n help='RTL-SDR device index')\n rtl_p.add_argument('-g',\n '--gain',\n default=40,\n type=float,\n help='RTL-SDR Rx gain')\n rtl_p.add_argument('-f',\n '--iq-file',\n default=None,\n help='File to read IQ samples from instead of reading '\n 'from the RTL-SDR in real-time')\n\n ldvb_p = p.add_argument_group('leandvb options')\n ldvb_p.add_argument(\n '-n',\n '--n-helpers',\n default=6,\n type=int,\n help='Number of instances of the external LDPC decoder \\\n to spawn as child processes')\n ldvb_p.add_argument(\n '-d',\n '--debug-dvbs2',\n action='count',\n default=0,\n help=\"Debug leandvb's DVB-S2 decoding. Use it multiple \"\n \"times to increase the debugging level\")\n ldvb_p.add_argument('-v',\n '--verbose',\n default=False,\n action='store_true',\n help='leandvb in verbose mode')\n ldvb_p.add_argument('--gui',\n default=False,\n action='store_true',\n help='GUI mode')\n ldvb_p.add_argument('--derotate',\n default=0,\n type=float,\n help='Frequency offset correction to apply in kHz')\n ldvb_p.add_argument('--fastlock',\n default=False,\n action='store_true',\n help='leandvb fast lock mode')\n ldvb_p.add_argument('--rrc-rej',\n default=30,\n type=int,\n help='leandvb RRC rej parameter')\n ldvb_p.add_argument('-m',\n '--modcod',\n choices=defs.modcods.keys(),\n default='qpsk3\/5',\n metavar='',\n help=\"DVB-S2 modulation and coding (MODCOD) scheme. \"\n \"Choose from: \" + \", \".join(defs.modcods.keys()))\n ldvb_p.add_argument('--ldpc-dec',\n default=\"ext\",\n choices=[\"int\", \"ext\"],\n help=\"LDPC decoder to use (internal or external)\")\n ldvb_p.add_argument('--ldpc-bf',\n default=100,\n help='Max number of iterations used by the internal \\\n LDPC decoder when not using an external LDPC tool')\n ldvb_p.add_argument('--ldpc-iterations',\n default=25,\n help='Max number of iterations used by the external \\\n LDPC decoder when using an external LDPC tool')\n ldvb_p.add_argument('--framesizes',\n type=int,\n default=1,\n choices=[0, 1, 2, 3],\n help=\"Bitmask of desired frame sizes (1=normal, \\\n 2=short)\")\n ldvb_p.add_argument('--no-tsp',\n default=False,\n action='store_true',\n help='Feed leandvb output to stdout instead of tsp')\n ldvb_p.add_argument('--pipe-size',\n default=32,\n type=int,\n help='Size in Mbytes of the input pipe file read by \\\n leandvb')\n\n # TSDuck Options\n tsp.add_to_parser(p)\n\n p.set_defaults(func=run, record=False)\n\n subsubparsers = p.add_subparsers(title='subcommands',\n help='Target sub-command')\n # IQ recording\n p2 = subsubparsers.add_parser(\n 'rec',\n description=\"Record IQ samples instead of \"\n \"feeding them into leandvb\",\n help='Record IQ samples',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p2.add_argument('-f',\n '--iq-file',\n default=\"blocksat.iq\",\n help='File on which to save IQ samples received with '\n 'the RTL-SDR.')\n p2.set_defaults(record=True)\n\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'sdr'",",","description","=","\"Launch SDR receiver\"",",","help","=","'Launch SDR receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","# Monitoring options","monitoring",".","add_to_parser","(","p",")","rtl_p","=","p",".","add_argument_group","(","'rtl_sdr options'",")","rtl_p",".","add_argument","(","'--sps'",",","default","=","2.0",",","type","=","float",",","help","=","'Samples per symbol, or, equivalently, the '","'target oversampling ratio'",")","rtl_p",".","add_argument","(","'--rtl-idx'",",","default","=","0",",","type","=","int",",","help","=","'RTL-SDR device index'",")","rtl_p",".","add_argument","(","'-g'",",","'--gain'",",","default","=","40",",","type","=","float",",","help","=","'RTL-SDR Rx gain'",")","rtl_p",".","add_argument","(","'-f'",",","'--iq-file'",",","default","=","None",",","help","=","'File to read IQ samples from instead of reading '","'from the RTL-SDR in real-time'",")","ldvb_p","=","p",".","add_argument_group","(","'leandvb options'",")","ldvb_p",".","add_argument","(","'-n'",",","'--n-helpers'",",","default","=","6",",","type","=","int",",","help","=","'Number of instances of the external LDPC decoder \\\n to spawn as child processes'",")","ldvb_p",".","add_argument","(","'-d'",",","'--debug-dvbs2'",",","action","=","'count'",",","default","=","0",",","help","=","\"Debug leandvb's DVB-S2 decoding. Use it multiple \"","\"times to increase the debugging level\"",")","ldvb_p",".","add_argument","(","'-v'",",","'--verbose'",",","default","=","False",",","action","=","'store_true'",",","help","=","'leandvb in verbose mode'",")","ldvb_p",".","add_argument","(","'--gui'",",","default","=","False",",","action","=","'store_true'",",","help","=","'GUI mode'",")","ldvb_p",".","add_argument","(","'--derotate'",",","default","=","0",",","type","=","float",",","help","=","'Frequency offset correction to apply in kHz'",")","ldvb_p",".","add_argument","(","'--fastlock'",",","default","=","False",",","action","=","'store_true'",",","help","=","'leandvb fast lock mode'",")","ldvb_p",".","add_argument","(","'--rrc-rej'",",","default","=","30",",","type","=","int",",","help","=","'leandvb RRC rej parameter'",")","ldvb_p",".","add_argument","(","'-m'",",","'--modcod'",",","choices","=","defs",".","modcods",".","keys","(",")",",","default","=","'qpsk3\/5'",",","metavar","=","''",",","help","=","\"DVB-S2 modulation and coding (MODCOD) scheme. \"","\"Choose from: \"","+","\", \"",".","join","(","defs",".","modcods",".","keys","(",")",")",")","ldvb_p",".","add_argument","(","'--ldpc-dec'",",","default","=","\"ext\"",",","choices","=","[","\"int\"",",","\"ext\"","]",",","help","=","\"LDPC decoder to use (internal or external)\"",")","ldvb_p",".","add_argument","(","'--ldpc-bf'",",","default","=","100",",","help","=","'Max number of iterations used by the internal \\\n LDPC decoder when not using an external LDPC tool'",")","ldvb_p",".","add_argument","(","'--ldpc-iterations'",",","default","=","25",",","help","=","'Max number of iterations used by the external \\\n LDPC decoder when using an external LDPC tool'",")","ldvb_p",".","add_argument","(","'--framesizes'",",","type","=","int",",","default","=","1",",","choices","=","[","0",",","1",",","2",",","3","]",",","help","=","\"Bitmask of desired frame sizes (1=normal, \\\n 2=short)\"",")","ldvb_p",".","add_argument","(","'--no-tsp'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Feed leandvb output to stdout instead of tsp'",")","ldvb_p",".","add_argument","(","'--pipe-size'",",","default","=","32",",","type","=","int",",","help","=","'Size in Mbytes of the input pipe file read by \\\n leandvb'",")","# TSDuck Options","tsp",".","add_to_parser","(","p",")","p",".","set_defaults","(","func","=","run",",","record","=","False",")","subsubparsers","=","p",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",")","# IQ recording","p2","=","subsubparsers",".","add_parser","(","'rec'",",","description","=","\"Record IQ samples instead of \"","\"feeding them into leandvb\"",",","help","=","'Record IQ samples'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p2",".","add_argument","(","'-f'",",","'--iq-file'",",","default","=","\"blocksat.iq\"",",","help","=","'File on which to save IQ samples received with '","'the RTL-SDR.'",")","p2",".","set_defaults","(","record","=","True",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/sdr.py#L141-L264"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/rp.py","language":"python","identifier":"_set_filters","parameters":"(dvb_ifs)","argument_list":"","return_statement":"","docstring":"Disable reverse-path (RP) filtering for the DVB interface\n\n There are two layers of RP filters, one specific to the network interface\n and a higher level that controls the configurations for all network\n interfaces. This function disables RP filtering on the top layer (for all\n interfaces) but then enables RP filtering individually on all interfaces,\n except the DVB-S2 interface of interst. This way, in the end, only the\n DVB-S2 interface has RP filtering disabled.\n\n If the top layer RP filter (the \"all\" rule) is already disabled, this\n function disables only the target DVB-S2 interface. This strategy is\n especially useful when multiple DVB-S2 interfaces are attached to the\n host. If one of them has already disabled the \"all\" rule, this function\n disables only the incoming DVB-S2 interface and doesn't re-enable the RP\n filters of the other interfaces, otherwise it would end up reactivating the\n filter for the other DVB-S2 interface(s).\n\n Args:\n dvb_ifs : List of target DVB-S2 network interfaces.","docstring_summary":"Disable reverse-path (RP) filtering for the DVB interface","docstring_tokens":["Disable","reverse","-","path","(","RP",")","filtering","for","the","DVB","interface"],"function":"def _set_filters(dvb_ifs):\n \"\"\"Disable reverse-path (RP) filtering for the DVB interface\n\n There are two layers of RP filters, one specific to the network interface\n and a higher level that controls the configurations for all network\n interfaces. This function disables RP filtering on the top layer (for all\n interfaces) but then enables RP filtering individually on all interfaces,\n except the DVB-S2 interface of interst. This way, in the end, only the\n DVB-S2 interface has RP filtering disabled.\n\n If the top layer RP filter (the \"all\" rule) is already disabled, this\n function disables only the target DVB-S2 interface. This strategy is\n especially useful when multiple DVB-S2 interfaces are attached to the\n host. If one of them has already disabled the \"all\" rule, this function\n disables only the incoming DVB-S2 interface and doesn't re-enable the RP\n filters of the other interfaces, otherwise it would end up reactivating the\n filter for the other DVB-S2 interface(s).\n\n Args:\n dvb_ifs : List of target DVB-S2 network interfaces.\n\n \"\"\"\n assert (isinstance(dvb_ifs, list))\n\n # If the \"all\" rule is already disabled, disable only the target DVB-S2\n # interface.\n if (_read_filter(\"all\", nodry=True) == 0):\n if (not runner.dry):\n print(\"RP filter for \\\"all\\\" interfaces is already disabled\")\n\n for dvb_if in dvb_ifs:\n _rm_filter(dvb_if)\n\n # If the \"all\" rule is enabled, disable it, and manually enable the RP\n # filtering on all other interfaces.\n else:\n # Check interfaces\n ifs = os.listdir(\"\/proc\/sys\/net\/ipv4\/conf\/\")\n\n # Enable all RP filters\n for interface in ifs:\n if (interface == \"all\" or interface == \"lo\"\n or interface in dvb_ifs):\n continue\n\n # Enable the RP filter if not enabled already.\n if (_read_filter(interface, nodry=True) > 0):\n if (not runner.dry):\n print(\"RP filter is already enabled on interface %s\" %\n (interface))\n else:\n _add_filter(interface)\n\n # Disable the overall RP filter\n _rm_filter(\"all\")\n\n # And disable RP filtering on the DVB interface\n for dvb_if in dvb_ifs:\n _rm_filter(dvb_if)","function_tokens":["def","_set_filters","(","dvb_ifs",")",":","assert","(","isinstance","(","dvb_ifs",",","list",")",")","# If the \"all\" rule is already disabled, disable only the target DVB-S2","# interface.","if","(","_read_filter","(","\"all\"",",","nodry","=","True",")","==","0",")",":","if","(","not","runner",".","dry",")",":","print","(","\"RP filter for \\\"all\\\" interfaces is already disabled\"",")","for","dvb_if","in","dvb_ifs",":","_rm_filter","(","dvb_if",")","# If the \"all\" rule is enabled, disable it, and manually enable the RP","# filtering on all other interfaces.","else",":","# Check interfaces","ifs","=","os",".","listdir","(","\"\/proc\/sys\/net\/ipv4\/conf\/\"",")","# Enable all RP filters","for","interface","in","ifs",":","if","(","interface","==","\"all\"","or","interface","==","\"lo\"","or","interface","in","dvb_ifs",")",":","continue","# Enable the RP filter if not enabled already.","if","(","_read_filter","(","interface",",","nodry","=","True",")",">","0",")",":","if","(","not","runner",".","dry",")",":","print","(","\"RP filter is already enabled on interface %s\"","%","(","interface",")",")","else",":","_add_filter","(","interface",")","# Disable the overall RP filter","_rm_filter","(","\"all\"",")","# And disable RP filtering on the DVB interface","for","dvb_if","in","dvb_ifs",":","_rm_filter","(","dvb_if",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/rp.py#L43-L101"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/rp.py","language":"python","identifier":"set_filters","parameters":"(dvb_ifs, prompt=True, dry=False)","argument_list":"","return_statement":"","docstring":"Disable reverse-path (RP) filtering for the DVB interfaces\n\n Args:\n dvb_ifs : list of DVB network interfaces\n prompt : Whether to prompt user before applying a configuration\n dry : Dry run mode","docstring_summary":"Disable reverse-path (RP) filtering for the DVB interfaces","docstring_tokens":["Disable","reverse","-","path","(","RP",")","filtering","for","the","DVB","interfaces"],"function":"def set_filters(dvb_ifs, prompt=True, dry=False):\n \"\"\"Disable reverse-path (RP) filtering for the DVB interfaces\n\n Args:\n dvb_ifs : list of DVB network interfaces\n prompt : Whether to prompt user before applying a configuration\n dry : Dry run mode\n\n \"\"\"\n assert (isinstance(dvb_ifs, list))\n runner.set_dry(dry)\n util.print_header(\"Reverse Path Filters\")\n\n # Check if the RP filters are already configured properly\n rp_filters_set = list()\n rp_filters_set.append(_read_filter(\"all\", nodry=True) == 0)\n for dvb_if in dvb_ifs:\n rp_filters_set.append(_read_filter(dvb_if, nodry=True) == 0)\n\n if (all(rp_filters_set)):\n print(\"Current RP filtering configurations are already OK\")\n print(\"Skipping...\")\n return\n\n util.fill_print(\"It will be necessary to reconfigure some reverse path \\\n (RP) filtering rules applied by the Linux kernel. This is required to \\\n prevent the filtering of the one-way Blockstream Satellite traffic.\")\n\n if (runner.dry):\n util.fill_print(\"The following command(s) would be executed to \\\n reconfigure the RP filters:\")\n\n if (runner.dry or (not prompt) or util.ask_yes_or_no(\"OK to proceed?\")):\n _set_filters(dvb_ifs)\n else:\n print(\"RP filtering configuration cancelled\")","function_tokens":["def","set_filters","(","dvb_ifs",",","prompt","=","True",",","dry","=","False",")",":","assert","(","isinstance","(","dvb_ifs",",","list",")",")","runner",".","set_dry","(","dry",")","util",".","print_header","(","\"Reverse Path Filters\"",")","# Check if the RP filters are already configured properly","rp_filters_set","=","list","(",")","rp_filters_set",".","append","(","_read_filter","(","\"all\"",",","nodry","=","True",")","==","0",")","for","dvb_if","in","dvb_ifs",":","rp_filters_set",".","append","(","_read_filter","(","dvb_if",",","nodry","=","True",")","==","0",")","if","(","all","(","rp_filters_set",")",")",":","print","(","\"Current RP filtering configurations are already OK\"",")","print","(","\"Skipping...\"",")","return","util",".","fill_print","(","\"It will be necessary to reconfigure some reverse path \\\n (RP) filtering rules applied by the Linux kernel. This is required to \\\n prevent the filtering of the one-way Blockstream Satellite traffic.\"",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"The following command(s) would be executed to \\\n reconfigure the RP filters:\"",")","if","(","runner",".","dry","or","(","not","prompt",")","or","util",".","ask_yes_or_no","(","\"OK to proceed?\"",")",")",":","_set_filters","(","dvb_ifs",")","else",":","print","(","\"RP filtering configuration cancelled\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/rp.py#L104-L139"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/rp.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Parser for rp command","docstring_summary":"Parser for rp command","docstring_tokens":["Parser","for","rp","command"],"function":"def subparser(subparsers):\n \"\"\"Parser for rp command\"\"\"\n p = subparsers.add_parser('reverse-path',\n aliases=['rp'],\n description=\"Set reverse path filters\",\n help='Set reverse path filters',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.add_argument('-i',\n '--interface',\n required=True,\n help='Network interface')\n p.add_argument('-y',\n '--yes',\n default=False,\n action='store_true',\n help=\"Default to answering Yes to configuration prompts\")\n p.add_argument(\"--dry-run\",\n action='store_true',\n default=False,\n help=\"Print all commands but do not execute them\")\n p.set_defaults(func=run)\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'reverse-path'",",","aliases","=","[","'rp'","]",",","description","=","\"Set reverse path filters\"",",","help","=","'Set reverse path filters'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","add_argument","(","'-i'",",","'--interface'",",","required","=","True",",","help","=","'Network interface'",")","p",".","add_argument","(","'-y'",",","'--yes'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Default to answering Yes to configuration prompts\"",")","p",".","add_argument","(","\"--dry-run\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Print all commands but do not execute them\"",")","p",".","set_defaults","(","func","=","run",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/rp.py#L142-L163"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/rp.py","language":"python","identifier":"run","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Call function that sets reverse path filters\n\n Handles the reverse-path subcommand","docstring_summary":"Call function that sets reverse path filters","docstring_tokens":["Call","function","that","sets","reverse","path","filters"],"function":"def run(args):\n \"\"\"Call function that sets reverse path filters\n\n Handles the reverse-path subcommand\n\n \"\"\"\n set_filters([args.interface], prompt=(not args.yes), dry=args.dry_run)","function_tokens":["def","run","(","args",")",":","set_filters","(","[","args",".","interface","]",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/rp.py#L166-L172"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/tsp.py","language":"python","identifier":"prints_to_stdout","parameters":"(args)","argument_list":"","return_statement":"return args.ts_monitor_bitrate or args.ts_monitor_sequence or \\\n args.ts_dump","docstring":"Check if tsp is configured to print to stdout","docstring_summary":"Check if tsp is configured to print to stdout","docstring_tokens":["Check","if","tsp","is","configured","to","print","to","stdout"],"function":"def prints_to_stdout(args):\n \"\"\"Check if tsp is configured to print to stdout\"\"\"\n return args.ts_monitor_bitrate or args.ts_monitor_sequence or \\\n args.ts_dump","function_tokens":["def","prints_to_stdout","(","args",")",":","return","args",".","ts_monitor_bitrate","or","args",".","ts_monitor_sequence","or","args",".","ts_dump"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/tsp.py#L173-L176"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/tsp.py","language":"python","identifier":"Tsp.gen_cmd","parameters":"(self, args, in_plugin=None)","argument_list":"","return_statement":"return True","docstring":"Generate the tsp command\n\n Args:\n in_plugin : List with input plugin command to be used by tsp.\n\n Rerturns:\n Boolean indicating whether a valid command was generated.","docstring_summary":"Generate the tsp command","docstring_tokens":["Generate","the","tsp","command"],"function":"def gen_cmd(self, args, in_plugin=None):\n \"\"\"Generate the tsp command\n\n Args:\n in_plugin : List with input plugin command to be used by tsp.\n\n Rerturns:\n Boolean indicating whether a valid command was generated.\n\n \"\"\"\n # cache the request for TS dumping\n self.ts_dump = args.ts_dump\n self.ts_dump_opts = args.ts_dump_opts\n\n self.cmd = cmd = [\n \"tsp\", \"--realtime\", \"--buffer-size-mb\",\n str(args.tsp_buffer_size_mb), \"--max-flushed-packets\",\n str(args.tsp_max_flushed_packets), \"--max-input-packets\",\n str(args.tsp_max_input_packets)\n ]\n\n if (in_plugin):\n cmd.extend(in_plugin)\n\n if (args.ts_analysis):\n logger.info(\"MPEG-TS analysis will be saved on file {}\".format(\n args.ts_analysis))\n if (not util.ask_yes_or_no(\"Proceed?\", default=\"y\")):\n return False\n cmd.extend([\"-P\", \"analyze\", \"-o\", args.ts_analysis])\n\n if (args.ts_monitor_bitrate):\n cmd.extend([\n \"-P\", \"bitrate_monitor\", \"-p\",\n str(args.ts_monitor_bitrate), \"--min\", \"0\"\n ])\n\n if (args.ts_monitor_sequence):\n cmd.extend([\"-P\", \"continuity\"])\n\n cmd.extend([\n \"-P\", \"mpe\", \"--pid\", \"-\".join([str(pid) for pid in defs.pids]),\n \"--udp-forward\", \"--local-address\", args.local_address\n ])\n\n # Output the MPEG TS stream to one of the following:\n # a) a file;\n # b) stdout (if using --ts-dump);\n # c) \/dev\/null (default).\n if (args.ts_file is not None):\n logger.info(\"MPEG TS output will be saved on file {}\".format(\n args.ts_file))\n if (not util.ask_yes_or_no(\"Proceed?\", default=\"y\")):\n return False\n cmd.extend([\"-O\", \"file\", args.ts_file])\n elif (not args.ts_dump):\n cmd.extend([\"-O\", \"drop\"])\n\n return True","function_tokens":["def","gen_cmd","(","self",",","args",",","in_plugin","=","None",")",":","# cache the request for TS dumping","self",".","ts_dump","=","args",".","ts_dump","self",".","ts_dump_opts","=","args",".","ts_dump_opts","self",".","cmd","=","cmd","=","[","\"tsp\"",",","\"--realtime\"",",","\"--buffer-size-mb\"",",","str","(","args",".","tsp_buffer_size_mb",")",",","\"--max-flushed-packets\"",",","str","(","args",".","tsp_max_flushed_packets",")",",","\"--max-input-packets\"",",","str","(","args",".","tsp_max_input_packets",")","]","if","(","in_plugin",")",":","cmd",".","extend","(","in_plugin",")","if","(","args",".","ts_analysis",")",":","logger",".","info","(","\"MPEG-TS analysis will be saved on file {}\"",".","format","(","args",".","ts_analysis",")",")","if","(","not","util",".","ask_yes_or_no","(","\"Proceed?\"",",","default","=","\"y\"",")",")",":","return","False","cmd",".","extend","(","[","\"-P\"",",","\"analyze\"",",","\"-o\"",",","args",".","ts_analysis","]",")","if","(","args",".","ts_monitor_bitrate",")",":","cmd",".","extend","(","[","\"-P\"",",","\"bitrate_monitor\"",",","\"-p\"",",","str","(","args",".","ts_monitor_bitrate",")",",","\"--min\"",",","\"0\"","]",")","if","(","args",".","ts_monitor_sequence",")",":","cmd",".","extend","(","[","\"-P\"",",","\"continuity\"","]",")","cmd",".","extend","(","[","\"-P\"",",","\"mpe\"",",","\"--pid\"",",","\"-\"",".","join","(","[","str","(","pid",")","for","pid","in","defs",".","pids","]",")",",","\"--udp-forward\"",",","\"--local-address\"",",","args",".","local_address","]",")","# Output the MPEG TS stream to one of the following:","# a) a file;","# b) stdout (if using --ts-dump);","# c) \/dev\/null (default).","if","(","args",".","ts_file","is","not","None",")",":","logger",".","info","(","\"MPEG TS output will be saved on file {}\"",".","format","(","args",".","ts_file",")",")","if","(","not","util",".","ask_yes_or_no","(","\"Proceed?\"",",","default","=","\"y\"",")",")",":","return","False","cmd",".","extend","(","[","\"-O\"",",","\"file\"",",","args",".","ts_file","]",")","elif","(","not","args",".","ts_dump",")",":","cmd",".","extend","(","[","\"-O\"",",","\"drop\"","]",")","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/tsp.py#L82-L140"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/tsp.py","language":"python","identifier":"Tsp.run","parameters":"(self, stdin=None)","argument_list":"","return_statement":"","docstring":"Run tsp\n\n Args:\n in_plugin : List with input plugin command to be used by tsp.\n stdin : Stdin to attach to the tsp process.\n\n Rerturns:\n Boolean indicating whether the process is running succesfully.","docstring_summary":"Run tsp","docstring_tokens":["Run","tsp"],"function":"def run(self, stdin=None):\n \"\"\"Run tsp\n\n Args:\n in_plugin : List with input plugin command to be used by tsp.\n stdin : Stdin to attach to the tsp process.\n\n Rerturns:\n Boolean indicating whether the process is running succesfully.\n\n \"\"\"\n # Create a .tsduck.lastcheck file on the home directory to skip the\n # TSDuck version check.\n Path(os.path.join(util.get_home_dir(), \".tsduck.lastcheck\")).touch()\n\n # When tsdump is enabled, hook tsp and tspdump through a pipe file (tsp\n # on the write side and tsdump on the read side)\n if (self.ts_dump):\n info_pipe = util.Pipe()\n stdout = info_pipe.w_fo\n else:\n stdout = None\n\n self.proc = subprocess.Popen(self.cmd, stdin=stdin, stdout=stdout)\n\n if (self.ts_dump):\n tsdump_cmd = ['tsdump']\n tsdump_cmd.extend(self.ts_dump_opts)\n self.dump_proc = subprocess.Popen(tsdump_cmd, stdin=info_pipe.r_fo)","function_tokens":["def","run","(","self",",","stdin","=","None",")",":","# Create a .tsduck.lastcheck file on the home directory to skip the","# TSDuck version check.","Path","(","os",".","path",".","join","(","util",".","get_home_dir","(",")",",","\".tsduck.lastcheck\"",")",")",".","touch","(",")","# When tsdump is enabled, hook tsp and tspdump through a pipe file (tsp","# on the write side and tsdump on the read side)","if","(","self",".","ts_dump",")",":","info_pipe","=","util",".","Pipe","(",")","stdout","=","info_pipe",".","w_fo","else",":","stdout","=","None","self",".","proc","=","subprocess",".","Popen","(","self",".","cmd",",","stdin","=","stdin",",","stdout","=","stdout",")","if","(","self",".","ts_dump",")",":","tsdump_cmd","=","[","'tsdump'","]","tsdump_cmd",".","extend","(","self",".","ts_dump_opts",")","self",".","dump_proc","=","subprocess",".","Popen","(","tsdump_cmd",",","stdin","=","info_pipe",".","r_fo",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/tsp.py#L142-L170"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"get_report_opts","parameters":"(args)","argument_list":"","return_statement":"return {\n 'cfg': args.cfg,\n 'cfg_dir': args.cfg_dir,\n 'dest_addr': args.report_dest,\n 'hostname': args.report_hostname,\n 'tls_cert': args.report_cert,\n 'tls_key': args.report_key,\n 'gnupghome': args.report_gnupghome,\n 'passphrase': args.report_passphrase\n }","docstring":"Extract the parser fields needed to construct a Reporter object","docstring_summary":"Extract the parser fields needed to construct a Reporter object","docstring_tokens":["Extract","the","parser","fields","needed","to","construct","a","Reporter","object"],"function":"def get_report_opts(args):\n \"\"\"Extract the parser fields needed to construct a Reporter object\"\"\"\n return {\n 'cfg': args.cfg,\n 'cfg_dir': args.cfg_dir,\n 'dest_addr': args.report_dest,\n 'hostname': args.report_hostname,\n 'tls_cert': args.report_cert,\n 'tls_key': args.report_key,\n 'gnupghome': args.report_gnupghome,\n 'passphrase': args.report_passphrase\n }","function_tokens":["def","get_report_opts","(","args",")",":","return","{","'cfg'",":","args",".","cfg",",","'cfg_dir'",":","args",".","cfg_dir",",","'dest_addr'",":","args",".","report_dest",",","'hostname'",":","args",".","report_hostname",",","'tls_cert'",":","args",".","report_cert",",","'tls_key'",":","args",".","report_key",",","'gnupghome'",":","args",".","report_gnupghome",",","'passphrase'",":","args",".","report_passphrase","}"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L18-L29"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"add_to_parser","parameters":"(parser)","argument_list":"","return_statement":"","docstring":"Add receiver monitoring options to parser","docstring_summary":"Add receiver monitoring options to parser","docstring_tokens":["Add","receiver","monitoring","options","to","parser"],"function":"def add_to_parser(parser):\n \"\"\"Add receiver monitoring options to parser\"\"\"\n m_p = parser.add_argument_group('receiver logging options')\n m_p.add_argument(\n '--log-scrolling',\n default=False,\n action='store_true',\n help='Print receiver logs line-by-line rather than repeatedly on the \\\n same line')\n m_p.add_argument('--log-file',\n default=False,\n action='store_true',\n help='Save receiver logs on a file')\n m_p.add_argument('--log-interval',\n type=float,\n default=1.0,\n help=\"Logging interval in seconds\")\n\n ms_p = parser.add_argument_group('receiver monitoring server options')\n ms_p.add_argument('--monitoring-server',\n default=False,\n action='store_true',\n help='Run HTTP server to monitor the receiver')\n ms_p.add_argument('--monitoring-port',\n default=defs.monitor_port,\n type=int,\n help='Monitoring server\\'s port')\n\n r_p = parser.add_argument_group('receiver reporting options')\n r_p.add_argument('--report',\n default=False,\n action='store_true',\n help='Report receiver metrics to a remote HTTP server')\n r_p.add_argument(\n '--report-dest',\n default=monitoring_api.metric_endpoint,\n help='Destination address in http:\/\/ip:port format. By default, '\n 'report to Blockstream\\'s Satellite Monitoring API')\n r_p.add_argument('--report-hostname', help='Reporter\\'s hostname')\n r_p.add_argument(\n '--report-cert',\n default=None,\n help=\"Certificate for client-side authentication with the destination\")\n r_p.add_argument(\n '--report-key',\n default=None,\n help=\"Private key for client-side authentication with the destination\")\n r_p.add_argument(\n '--report-gnupghome',\n default=\".gnupg\",\n help=\"GnuPG home directory, by default created inside the config \"\n \"directory specified via --cfg-dir option. This option is used when \"\n \"reporting to Blockstream's Satellite Monitoring API only, where it \"\n \"determines the name of the directory (inside --cfg-dir) that holds \"\n \"the key for authentication with the API\")\n r_p.add_argument(\n '--report-passphrase',\n default=None,\n help=\"Passphrase to the private GnuPG key used to sign receiver \"\n \"status reports sent to Blockstream's Satellite Monitoring API. If \"\n \"undefined (default), the program prompts for this passphrase instead.\"\n )","function_tokens":["def","add_to_parser","(","parser",")",":","m_p","=","parser",".","add_argument_group","(","'receiver logging options'",")","m_p",".","add_argument","(","'--log-scrolling'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Print receiver logs line-by-line rather than repeatedly on the \\\n same line'",")","m_p",".","add_argument","(","'--log-file'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Save receiver logs on a file'",")","m_p",".","add_argument","(","'--log-interval'",",","type","=","float",",","default","=","1.0",",","help","=","\"Logging interval in seconds\"",")","ms_p","=","parser",".","add_argument_group","(","'receiver monitoring server options'",")","ms_p",".","add_argument","(","'--monitoring-server'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Run HTTP server to monitor the receiver'",")","ms_p",".","add_argument","(","'--monitoring-port'",",","default","=","defs",".","monitor_port",",","type","=","int",",","help","=","'Monitoring server\\'s port'",")","r_p","=","parser",".","add_argument_group","(","'receiver reporting options'",")","r_p",".","add_argument","(","'--report'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Report receiver metrics to a remote HTTP server'",")","r_p",".","add_argument","(","'--report-dest'",",","default","=","monitoring_api",".","metric_endpoint",",","help","=","'Destination address in http:\/\/ip:port format. By default, '","'report to Blockstream\\'s Satellite Monitoring API'",")","r_p",".","add_argument","(","'--report-hostname'",",","help","=","'Reporter\\'s hostname'",")","r_p",".","add_argument","(","'--report-cert'",",","default","=","None",",","help","=","\"Certificate for client-side authentication with the destination\"",")","r_p",".","add_argument","(","'--report-key'",",","default","=","None",",","help","=","\"Private key for client-side authentication with the destination\"",")","r_p",".","add_argument","(","'--report-gnupghome'",",","default","=","\".gnupg\"",",","help","=","\"GnuPG home directory, by default created inside the config \"","\"directory specified via --cfg-dir option. This option is used when \"","\"reporting to Blockstream's Satellite Monitoring API only, where it \"","\"determines the name of the directory (inside --cfg-dir) that holds \"","\"the key for authentication with the API\"",")","r_p",".","add_argument","(","'--report-passphrase'",",","default","=","None",",","help","=","\"Passphrase to the private GnuPG key used to sign receiver \"","\"status reports sent to Blockstream's Satellite Monitoring API. If \"","\"undefined (default), the program prompts for this passphrase instead.\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L378-L439"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Reporter.__init__","parameters":"(self,\n cfg,\n cfg_dir,\n dest_addr,\n hostname=None,\n tls_cert=None,\n tls_key=None,\n gnupghome=None,\n passphrase=None)","argument_list":"","return_statement":"","docstring":"Reporter Constructor\n\n Args:\n cfg : User configuration\n cfg_dir : Configuration directory\n dest_addr : Remote server address\n hostname : Hostname used to identify the reports\n tls_cert : Optional client side certificate for TLS authentication\n tls_key : Key associated with the client side certificate\n gnupghome : GnuPG home directory used when reporting to\n Blockstream's monitoring API\n passphrase : Passphrase to the private key used when reporting to\n Blockstream's monitoring API. If None, it will be\n obtained by prompting the user.","docstring_summary":"Reporter Constructor","docstring_tokens":["Reporter","Constructor"],"function":"def __init__(self,\n cfg,\n cfg_dir,\n dest_addr,\n hostname=None,\n tls_cert=None,\n tls_key=None,\n gnupghome=None,\n passphrase=None):\n \"\"\"Reporter Constructor\n\n Args:\n cfg : User configuration\n cfg_dir : Configuration directory\n dest_addr : Remote server address\n hostname : Hostname used to identify the reports\n tls_cert : Optional client side certificate for TLS authentication\n tls_key : Key associated with the client side certificate\n gnupghome : GnuPG home directory used when reporting to\n Blockstream's monitoring API\n passphrase : Passphrase to the private key used when reporting to\n Blockstream's monitoring API. If None, it will be\n obtained by prompting the user.\n\n \"\"\"\n info = config.read_cfg_file(cfg, cfg_dir)\n assert (info is not None)\n\n # Validate the satellite\n satellite = info['sat']['alias']\n assert (satellite is not None), \"Reporting satellite undefined\"\n assert (satellite in sats), \"Invalid satellite\"\n self.satellite = satellite\n\n # Destination address, hostname, and client side cert\n self.dest_addr = dest_addr\n self.hostname = hostname\n self.tls_cert = tls_cert\n self.tls_key = tls_key\n\n # If the report destination address corresponds to Blockstream's\n # Monitoring API (the default), create the object to handle the\n # interaction with this API (e.g., registration).\n if (dest_addr == monitoring_api.metric_endpoint):\n self.bs_monitoring = monitoring_api.BsMonitoring(\n cfg, cfg_dir, gnupghome, passphrase)\n else:\n self.bs_monitoring = None\n\n logger.info(\"Reporting Rx status to {} \".format(self.dest_addr))","function_tokens":["def","__init__","(","self",",","cfg",",","cfg_dir",",","dest_addr",",","hostname","=","None",",","tls_cert","=","None",",","tls_key","=","None",",","gnupghome","=","None",",","passphrase","=","None",")",":","info","=","config",".","read_cfg_file","(","cfg",",","cfg_dir",")","assert","(","info","is","not","None",")","# Validate the satellite","satellite","=","info","[","'sat'","]","[","'alias'","]","assert","(","satellite","is","not","None",")",",","\"Reporting satellite undefined\"","assert","(","satellite","in","sats",")",",","\"Invalid satellite\"","self",".","satellite","=","satellite","# Destination address, hostname, and client side cert","self",".","dest_addr","=","dest_addr","self",".","hostname","=","hostname","self",".","tls_cert","=","tls_cert","self",".","tls_key","=","tls_key","# If the report destination address corresponds to Blockstream's","# Monitoring API (the default), create the object to handle the","# interaction with this API (e.g., registration).","if","(","dest_addr","==","monitoring_api",".","metric_endpoint",")",":","self",".","bs_monitoring","=","monitoring_api",".","BsMonitoring","(","cfg",",","cfg_dir",",","gnupghome",",","passphrase",")","else",":","self",".","bs_monitoring","=","None","logger",".","info","(","\"Reporting Rx status to {} \"",".","format","(","self",".","dest_addr",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L38-L87"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Reporter.send","parameters":"(self, metrics)","argument_list":"","return_statement":"","docstring":"Save measurement on database\n\n Args:\n metrics : Dictionary with receiver metrics to send over the report","docstring_summary":"Save measurement on database","docstring_tokens":["Save","measurement","on","database"],"function":"def send(self, metrics):\n \"\"\"Save measurement on database\n\n Args:\n metrics : Dictionary with receiver metrics to send over the report\n \"\"\"\n # When the receiver is not registered with the monitoring API, the\n # sign-up procedure runs. However, this procedure can only work if the\n # receiver is locked, given that it requires reception of a validation\n # code sent exclusively over satellite. Hence, the registration routine\n # (running on a thread) waits until a threading event is set below to\n # indicate the Rx lock:\n if (self.bs_monitoring and not self.bs_monitoring.registered):\n if ('lock' in metrics and metrics['lock']):\n self.bs_monitoring.rx_lock_event.set()\n\n # If the registration procedure has already stopped and failed, do\n # not proceed. Reporting would otherwise fail anyway, given that\n # the monitoring server does not accept reports from non-registered\n # receivers. Just warn the user and stop right here.\n if (self.bs_monitoring.registration_failure):\n print()\n logger.error(\"Report failed: registration incomplete \"\n \"(relaunch receiver and try again)\")\n\n # Don't send reports to the monitoring API until the receiver is\n # properly registered and verified\n return\n\n data = {}\n data.update(metrics)\n\n # When reporting to Blockstream's Monitoring API, sign every set of\n # reported data using the local GPG key and don't send the satellite\n # nor the hostname on the requests. This information is already\n # associated with the account registered with the Monitoring API. In\n # contrast, when reporting to a general-purpose server, do include the\n # satellite and hostname information if defined.\n if (self.bs_monitoring is None):\n data[\"satellite\"] = self.satellite,\n if (self.hostname):\n data['hostname'] = self.hostname\n else:\n self.bs_monitoring.sign_report(data)\n\n logger.debug(\"Report {} to {}\".format(data, self.dest_addr))\n\n try:\n r = requests.post(self.dest_addr,\n json=data,\n cert=(self.tls_cert, self.tls_key))\n if (r.status_code != requests.codes.ok):\n print()\n logger.error(\"Report failed: \" + r.text)\n except requests.exceptions.ConnectionError as e:\n print()\n logger.error(\"Report failed: \" + str(e))","function_tokens":["def","send","(","self",",","metrics",")",":","# When the receiver is not registered with the monitoring API, the","# sign-up procedure runs. However, this procedure can only work if the","# receiver is locked, given that it requires reception of a validation","# code sent exclusively over satellite. Hence, the registration routine","# (running on a thread) waits until a threading event is set below to","# indicate the Rx lock:","if","(","self",".","bs_monitoring","and","not","self",".","bs_monitoring",".","registered",")",":","if","(","'lock'","in","metrics","and","metrics","[","'lock'","]",")",":","self",".","bs_monitoring",".","rx_lock_event",".","set","(",")","# If the registration procedure has already stopped and failed, do","# not proceed. Reporting would otherwise fail anyway, given that","# the monitoring server does not accept reports from non-registered","# receivers. Just warn the user and stop right here.","if","(","self",".","bs_monitoring",".","registration_failure",")",":","print","(",")","logger",".","error","(","\"Report failed: registration incomplete \"","\"(relaunch receiver and try again)\"",")","# Don't send reports to the monitoring API until the receiver is","# properly registered and verified","return","data","=","{","}","data",".","update","(","metrics",")","# When reporting to Blockstream's Monitoring API, sign every set of","# reported data using the local GPG key and don't send the satellite","# nor the hostname on the requests. This information is already","# associated with the account registered with the Monitoring API. In","# contrast, when reporting to a general-purpose server, do include the","# satellite and hostname information if defined.","if","(","self",".","bs_monitoring","is","None",")",":","data","[","\"satellite\"","]","=","self",".","satellite",",","if","(","self",".","hostname",")",":","data","[","'hostname'","]","=","self",".","hostname","else",":","self",".","bs_monitoring",".","sign_report","(","data",")","logger",".","debug","(","\"Report {} to {}\"",".","format","(","data",",","self",".","dest_addr",")",")","try",":","r","=","requests",".","post","(","self",".","dest_addr",",","json","=","data",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","(","r",".","status_code","!=","requests",".","codes",".","ok",")",":","print","(",")","logger",".","error","(","\"Report failed: \"","+","r",".","text",")","except","requests",".","exceptions",".","ConnectionError","as","e",":","print","(",")","logger",".","error","(","\"Report failed: \"","+","str","(","e",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L89-L145"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor.__init__","parameters":"(self,\n cfg_dir,\n logfile=False,\n scroll=False,\n echo=True,\n min_interval=1.0,\n server=False,\n port=defs.monitor_port,\n report=False,\n report_opts={},\n utc=True)","argument_list":"","return_statement":"","docstring":"Monitor Constructor\n\n Args:\n cfg_dir : Configuration directory where logs are saved\n logfile : Whether to dump logs into a file\n scroll : Whether to print logs with scrolling or continuously\n overwrite the same line\n echo : Whether to echo (print) every update to receiver\n metrics to stdout.\n min_interval : Minimum interval in seconds between logs echoed or\n saved.\n server : Launch server to reply the receiver status via HTTP.\n port : Server's HTTP port, if enabled.\n report : Whether to report the receiver status over HTTP to\n a remote address.\n report_opts : Reporter options.\n utc : Whether to print logs in UTC time.","docstring_summary":"Monitor Constructor","docstring_tokens":["Monitor","Constructor"],"function":"def __init__(self,\n cfg_dir,\n logfile=False,\n scroll=False,\n echo=True,\n min_interval=1.0,\n server=False,\n port=defs.monitor_port,\n report=False,\n report_opts={},\n utc=True):\n \"\"\"Monitor Constructor\n\n Args:\n cfg_dir : Configuration directory where logs are saved\n logfile : Whether to dump logs into a file\n scroll : Whether to print logs with scrolling or continuously\n overwrite the same line\n echo : Whether to echo (print) every update to receiver\n metrics to stdout.\n min_interval : Minimum interval in seconds between logs echoed or\n saved.\n server : Launch server to reply the receiver status via HTTP.\n port : Server's HTTP port, if enabled.\n report : Whether to report the receiver status over HTTP to\n a remote address.\n report_opts : Reporter options.\n utc : Whether to print logs in UTC time.\n\n \"\"\"\n self.cfg_dir = cfg_dir\n self.logfile = None\n self.scroll = scroll\n self.echo = echo\n self.min_interval = min_interval\n self.report = report\n self.utc = utc\n if (logfile):\n self._setup_logfile()\n\n # Supported receiver metrics, with their labels and printing formats\n self._metrics = {\n 'lock': {\n 'label': 'Lock',\n 'format_str': ''\n },\n 'level': {\n 'label': 'Level',\n 'format_str': '.2f'\n },\n 'snr': {\n 'label': 'SNR',\n 'format_str': '.2f'\n },\n 'ber': {\n 'label': 'BER',\n 'format_str': '.2e'\n },\n 'quality': {\n 'label': 'Signal Quality',\n 'format_str': '.1f'\n },\n 'pkt_err': {\n 'label': 'Packet Errors',\n 'format_str': 'd'\n }\n }\n self.stats = {}\n\n # Reporter sessions\n if (report):\n self.reporter = Reporter(**report_opts)\n\n # State\n self.t_last_print = time.time()\n\n # Launch HTTP server on a daemon thread\n if (server):\n self.sever_thread = threading.Thread(target=self._run_server,\n args=(port, ),\n daemon=True)\n self.sever_thread.start()","function_tokens":["def","__init__","(","self",",","cfg_dir",",","logfile","=","False",",","scroll","=","False",",","echo","=","True",",","min_interval","=","1.0",",","server","=","False",",","port","=","defs",".","monitor_port",",","report","=","False",",","report_opts","=","{","}",",","utc","=","True",")",":","self",".","cfg_dir","=","cfg_dir","self",".","logfile","=","None","self",".","scroll","=","scroll","self",".","echo","=","echo","self",".","min_interval","=","min_interval","self",".","report","=","report","self",".","utc","=","utc","if","(","logfile",")",":","self",".","_setup_logfile","(",")","# Supported receiver metrics, with their labels and printing formats","self",".","_metrics","=","{","'lock'",":","{","'label'",":","'Lock'",",","'format_str'",":","''","}",",","'level'",":","{","'label'",":","'Level'",",","'format_str'",":","'.2f'","}",",","'snr'",":","{","'label'",":","'SNR'",",","'format_str'",":","'.2f'","}",",","'ber'",":","{","'label'",":","'BER'",",","'format_str'",":","'.2e'","}",",","'quality'",":","{","'label'",":","'Signal Quality'",",","'format_str'",":","'.1f'","}",",","'pkt_err'",":","{","'label'",":","'Packet Errors'",",","'format_str'",":","'d'","}","}","self",".","stats","=","{","}","# Reporter sessions","if","(","report",")",":","self",".","reporter","=","Reporter","(","*","*","report_opts",")","# State","self",".","t_last_print","=","time",".","time","(",")","# Launch HTTP server on a daemon thread","if","(","server",")",":","self",".","sever_thread","=","threading",".","Thread","(","target","=","self",".","_run_server",",","args","=","(","port",",",")",",","daemon","=","True",")","self",".","sever_thread",".","start","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L172-L253"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor._run_server","parameters":"(self, port)","argument_list":"","return_statement":"","docstring":"Run HTTP server with access to the Monitor object","docstring_summary":"Run HTTP server with access to the Monitor object","docstring_tokens":["Run","HTTP","server","with","access","to","the","Monitor","object"],"function":"def _run_server(self, port):\n \"\"\"Run HTTP server with access to the Monitor object\"\"\"\n server_address = ('', port)\n Server.monitor = self\n self.httpd = HTTPServer(server_address, Server)\n self.httpd.serve_forever()","function_tokens":["def","_run_server","(","self",",","port",")",":","server_address","=","(","''",",","port",")","Server",".","monitor","=","self","self",".","httpd","=","HTTPServer","(","server_address",",","Server",")","self",".","httpd",".","serve_forever","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L255-L260"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor.__str__","parameters":"(self)","argument_list":"","return_statement":"return string","docstring":"Return string containing the receiver stats","docstring_summary":"Return string containing the receiver stats","docstring_tokens":["Return","string","containing","the","receiver","stats"],"function":"def __str__(self):\n \"\"\"Return string containing the receiver stats\"\"\"\n if (self.utc):\n timestamp = time.gmtime()\n else:\n timestamp = time.localtime()\n t_now = time.strftime(\"%Y-%m-%d %H:%M:%S\", timestamp)\n\n string = \"{} \".format(t_now)\n\n for key in self._metrics.keys():\n if key in self.stats:\n val = self.stats[key]\n # Label=Value\n string += \" {} = {:{fmt_str}}\".format(\n self._metrics[key]['label'],\n val[0],\n fmt_str=self._metrics[key]['format_str'],\n )\n # Unit\n if (not math.isnan(val[0]) and val[1]):\n string += val[1]\n\n string += \";\"\n\n return string","function_tokens":["def","__str__","(","self",")",":","if","(","self",".","utc",")",":","timestamp","=","time",".","gmtime","(",")","else",":","timestamp","=","time",".","localtime","(",")","t_now","=","time",".","strftime","(","\"%Y-%m-%d %H:%M:%S\"",",","timestamp",")","string","=","\"{} \"",".","format","(","t_now",")","for","key","in","self",".","_metrics",".","keys","(",")",":","if","key","in","self",".","stats",":","val","=","self",".","stats","[","key","]","# Label=Value","string","+=","\" {} = {:{fmt_str}}\"",".","format","(","self",".","_metrics","[","key","]","[","'label'","]",",","val","[","0","]",",","fmt_str","=","self",".","_metrics","[","key","]","[","'format_str'","]",",",")","# Unit","if","(","not","math",".","isnan","(","val","[","0","]",")","and","val","[","1","]",")",":","string","+=","val","[","1","]","string","+=","\";\"","return","string"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L262-L287"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor._setup_logfile","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Setup directory and file for logs","docstring_summary":"Setup directory and file for logs","docstring_tokens":["Setup","directory","and","file","for","logs"],"function":"def _setup_logfile(self):\n \"\"\"Setup directory and file for logs\"\"\"\n log_dir = os.path.join(self.cfg_dir, \"logs\")\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n name = time.strftime(\"%Y%m%d-%H%M%S\") + \".log\"\n self.logfile = os.path.join(log_dir, name)\n logger.info(\"Saving logs at {}\".format(self.logfile))","function_tokens":["def","_setup_logfile","(","self",")",":","log_dir","=","os",".","path",".","join","(","self",".","cfg_dir",",","\"logs\"",")","if","not","os",".","path",".","exists","(","log_dir",")",":","os",".","makedirs","(","log_dir",")","name","=","time",".","strftime","(","\"%Y%m%d-%H%M%S\"",")","+","\".log\"","self",".","logfile","=","os",".","path",".","join","(","log_dir",",","name",")","logger",".","info","(","\"Saving logs at {}\"",".","format","(","self",".","logfile",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L289-L297"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor.get_stats","parameters":"(self, strip_unit=True)","argument_list":"","return_statement":"return res","docstring":"Get dictionary with the receiver stats\n\n Args:\n strip unit : Return the values directly, instead of tuples\n containing the value and its unit.","docstring_summary":"Get dictionary with the receiver stats","docstring_tokens":["Get","dictionary","with","the","receiver","stats"],"function":"def get_stats(self, strip_unit=True):\n \"\"\"Get dictionary with the receiver stats\n\n Args:\n strip unit : Return the values directly, instead of tuples\n containing the value and its unit.\n\n \"\"\"\n if (not strip_unit):\n res = self.stats.copy()\n else:\n res = {}\n for key, val in self.stats.items():\n res[key] = val[0]\n\n return res","function_tokens":["def","get_stats","(","self",",","strip_unit","=","True",")",":","if","(","not","strip_unit",")",":","res","=","self",".","stats",".","copy","(",")","else",":","res","=","{","}","for","key",",","val","in","self",".","stats",".","items","(",")",":","res","[","key","]","=","val","[","0","]","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L299-L314"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring.py","language":"python","identifier":"Monitor.update","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Update the receiver stats kept internally\n\n Args:\n data : Dictionary of tuples corresponding to the receiver metrics.\n Each tuple should consist of the value and its unit.","docstring_summary":"Update the receiver stats kept internally","docstring_tokens":["Update","the","receiver","stats","kept","internally"],"function":"def update(self, data):\n \"\"\"Update the receiver stats kept internally\n\n Args:\n data : Dictionary of tuples corresponding to the receiver metrics.\n Each tuple should consist of the value and its unit.\n\n \"\"\"\n\n # The input should be a dictionary of tuples\n assert (isinstance(data, dict))\n assert (all([isinstance(x, tuple) for x in data.values()]))\n\n # All keys in the input dictionary must be supported receiver metrics\n assert (all([k in self._metrics for k in data.keys()]))\n\n # Copy all the data\n self.stats = data\n\n # Is it time to log a new line?\n t_now = time.time()\n if (t_now - self.t_last_print) < self.min_interval:\n return\n\n self.t_last_print = t_now\n\n # Append metrics to log file\n if (self.logfile):\n with open(self.logfile, 'a') as fd:\n fd.write(str(self) + \"\\n\")\n\n # Report over HTTP to a remote address\n if (self.report):\n self.reporter.send(self.get_stats())\n # If the reporter object is configured to report to the Monitoring\n # API but, at this point, it is still waiting for registration to\n # complete, don't log the status to the console yet. Otherwise, the\n # user would likely miss the logs indicating completion of the\n # registration procedure. On the other hand, if a log file is\n # enabled, it is OK to log into it throughout the registration.\n #\n # Besides, if the reporter is configured to report to the\n # Monitoring API and the registration is not complete yet, the\n # above call does not really send the report yet. Nevertheless, it\n # is still required. Refer to the implementation.\n #\n # As soon as the registration procedure ends (as indicated by the\n # \"registration_running\" flag), console logs are reactivated, even\n # if the registration fails.\n if (self.reporter.bs_monitoring is not None\n and not self.reporter.bs_monitoring.registered\n and self.reporter.bs_monitoring.registration_running):\n return\n\n # Print to console\n if (self.echo):\n print_end = '\\n' if self.scroll else '\\r'\n if (not self.scroll):\n sys.stdout.write(\"\\033[K\")\n print(str(self), end=print_end)","function_tokens":["def","update","(","self",",","data",")",":","# The input should be a dictionary of tuples","assert","(","isinstance","(","data",",","dict",")",")","assert","(","all","(","[","isinstance","(","x",",","tuple",")","for","x","in","data",".","values","(",")","]",")",")","# All keys in the input dictionary must be supported receiver metrics","assert","(","all","(","[","k","in","self",".","_metrics","for","k","in","data",".","keys","(",")","]",")",")","# Copy all the data","self",".","stats","=","data","# Is it time to log a new line?","t_now","=","time",".","time","(",")","if","(","t_now","-","self",".","t_last_print",")","<","self",".","min_interval",":","return","self",".","t_last_print","=","t_now","# Append metrics to log file","if","(","self",".","logfile",")",":","with","open","(","self",".","logfile",",","'a'",")","as","fd",":","fd",".","write","(","str","(","self",")","+","\"\\n\"",")","# Report over HTTP to a remote address","if","(","self",".","report",")",":","self",".","reporter",".","send","(","self",".","get_stats","(",")",")","# If the reporter object is configured to report to the Monitoring","# API but, at this point, it is still waiting for registration to","# complete, don't log the status to the console yet. Otherwise, the","# user would likely miss the logs indicating completion of the","# registration procedure. On the other hand, if a log file is","# enabled, it is OK to log into it throughout the registration.","#","# Besides, if the reporter is configured to report to the","# Monitoring API and the registration is not complete yet, the","# above call does not really send the report yet. Nevertheless, it","# is still required. Refer to the implementation.","#","# As soon as the registration procedure ends (as indicated by the","# \"registration_running\" flag), console logs are reactivated, even","# if the registration fails.","if","(","self",".","reporter",".","bs_monitoring","is","not","None","and","not","self",".","reporter",".","bs_monitoring",".","registered","and","self",".","reporter",".","bs_monitoring",".","registration_running",")",":","return","# Print to console","if","(","self",".","echo",")",":","print_end","=","'\\n'","if","self",".","scroll","else","'\\r'","if","(","not","self",".","scroll",")",":","sys",".","stdout",".","write","(","\"\\033[K\"",")","print","(","str","(","self",")",",","end","=","print_end",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring.py#L316-L375"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"parse_http_header","parameters":"(header, header_key)","argument_list":"","return_statement":"","docstring":"Parse HTTP header value\n\n Parse the value of a specific header from a RAW HTTP response.\n\n :param header: String containing the RAW HTTP response and headers\n :type header: str\n :param header_key: The header name of which to extract a value from\n :type header_key: str\n :return: The value of the header\n :rtype: str","docstring_summary":"Parse HTTP header value","docstring_tokens":["Parse","HTTP","header","value"],"function":"def parse_http_header(header, header_key):\n \"\"\"Parse HTTP header value\n\n Parse the value of a specific header from a RAW HTTP response.\n\n :param header: String containing the RAW HTTP response and headers\n :type header: str\n :param header_key: The header name of which to extract a value from\n :type header_key: str\n :return: The value of the header\n :rtype: str\n\n \"\"\"\n split_headers = header.split('\\r\\n')\n\n for entry in split_headers:\n header = entry.strip().split(':', 1)\n\n if header[0].strip().lower() == header_key.strip().lower():\n return ''.join(header[1::]).split()[0]","function_tokens":["def","parse_http_header","(","header",",","header_key",")",":","split_headers","=","header",".","split","(","'\\r\\n'",")","for","entry","in","split_headers",":","header","=","entry",".","strip","(",")",".","split","(","':'",",","1",")","if","header","[","0","]",".","strip","(",")",".","lower","(",")","==","header_key",".","strip","(",")",".","lower","(",")",":","return","''",".","join","(","header","[","1",":",":","]",")",".","split","(",")","[","0","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L44-L63"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"make_http_request","parameters":"(url, data=None, headers=None)","argument_list":"","return_statement":"return urllib.request.urlopen(request)","docstring":"Helper function for making HTTP requests\n\n Helper function for making HTTP requests using urllib.\n\n :param url: The URL to which a request should be made\n :type url: str\n :param data: Provide data for the request. Request method will be set to\n POST if data is provided\n :type data: str\n :param headers: Provide headers to send with the request\n :type headers: dict\n :return: A urllib.Request.urlopen object\n :rtype: urllib.Request.urlopen","docstring_summary":"Helper function for making HTTP requests","docstring_tokens":["Helper","function","for","making","HTTP","requests"],"function":"def make_http_request(url, data=None, headers=None):\n \"\"\"Helper function for making HTTP requests\n\n Helper function for making HTTP requests using urllib.\n\n :param url: The URL to which a request should be made\n :type url: str\n :param data: Provide data for the request. Request method will be set to\n POST if data is provided\n :type data: str\n :param headers: Provide headers to send with the request\n :type headers: dict\n :return: A urllib.Request.urlopen object\n :rtype: urllib.Request.urlopen\n\n \"\"\"\n if not headers:\n headers = {}\n\n # If data is provided the request method will automatically be set to POST\n # by urllib\n request = urllib.request.Request(url, data=data, headers=headers)\n return urllib.request.urlopen(request)","function_tokens":["def","make_http_request","(","url",",","data","=","None",",","headers","=","None",")",":","if","not","headers",":","headers","=","{","}","# If data is provided the request method will automatically be set to POST","# by urllib","request","=","urllib",".","request",".","Request","(","url",",","data","=","data",",","headers","=","headers",")","return","urllib",".","request",".","urlopen","(","request",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L66-L88"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"_device_description_required","parameters":"(func)","argument_list":"","return_statement":"return wrapper","docstring":"Decorator for checking whether the device description is available on a\n device.","docstring_summary":"Decorator for checking whether the device description is available on a\n device.","docstring_tokens":["Decorator","for","checking","whether","the","device","description","is","available","on","a","device","."],"function":"def _device_description_required(func):\n \"\"\"Decorator for checking whether the device description is available on a\n device.\n\n \"\"\"\n @wraps(func)\n def wrapper(device, *args, **kwargs):\n if device.description is None:\n raise NotRetrievedError(\n 'No device description retrieved for this device.')\n elif device.description == NotAvailableError:\n return\n return func(device, *args, **kwargs)\n\n return wrapper","function_tokens":["def","_device_description_required","(","func",")",":","@","wraps","(","func",")","def","wrapper","(","device",",","*","args",",","*","*","kwargs",")",":","if","device",".","description","is","None",":","raise","NotRetrievedError","(","'No device description retrieved for this device.'",")","elif","device",".","description","==","NotAvailableError",":","return","return","func","(","device",",","*","args",",","*","*","kwargs",")","return","wrapper"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L91-L105"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"_get_if_index","parameters":"(ifname, fd)","argument_list":"","return_statement":"return int(struct.unpack('16si', res)[1])","docstring":"Get the index corresponding to interface ifname used by socket fd","docstring_summary":"Get the index corresponding to interface ifname used by socket fd","docstring_tokens":["Get","the","index","corresponding","to","interface","ifname","used","by","socket","fd"],"function":"def _get_if_index(ifname, fd):\n \"\"\"Get the index corresponding to interface ifname used by socket fd\"\"\"\n ifreq = struct.pack('16si', ifname.encode(), 0)\n res = fcntl.ioctl(fd, SIOCGIFINDEX, ifreq)\n return int(struct.unpack('16si', res)[1])","function_tokens":["def","_get_if_index","(","ifname",",","fd",")",":","ifreq","=","struct",".","pack","(","'16si'",",","ifname",".","encode","(",")",",","0",")","res","=","fcntl",".","ioctl","(","fd",",","SIOCGIFINDEX",",","ifreq",")","return","int","(","struct",".","unpack","(","'16si'",",","res",")","[","1","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L108-L112"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"SSDPDevice.get_friendly_name","parameters":"(self)","argument_list":"","return_statement":"return self.friendly_name","docstring":"Get the friendly name for the device\n\n Gets the device's friendly name\n\n :return: Friendly name of the device\n :rtype: str","docstring_summary":"Get the friendly name for the device","docstring_tokens":["Get","the","friendly","name","for","the","device"],"function":"def get_friendly_name(self):\n \"\"\"Get the friendly name for the device\n\n Gets the device's friendly name\n\n :return: Friendly name of the device\n :rtype: str\n\n \"\"\"\n return self.friendly_name","function_tokens":["def","get_friendly_name","(","self",")",":","return","self",".","friendly_name"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L141-L150"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"SSDPHeader.__init__","parameters":"(self, **headers)","argument_list":"","return_statement":"","docstring":"Example M-SEARCH header:\n ------------------------------------------------------------------------\n M-SEARCH * HTTP\/1.1 SSDP method for search requests\n HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED)\n MAN: \"ssdp:discover\" HTTP Extension Framework scope (REQUIRED)\n MX: 2 Maximum wait time in seconds (REQUIRED)\n ST: upnp:rootdevice Search target (REQUIRED)\n ------------------------------------------------------------------------","docstring_summary":"Example M-SEARCH header:\n ------------------------------------------------------------------------\n M-SEARCH * HTTP\/1.1 SSDP method for search requests\n HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED)\n MAN: \"ssdp:discover\" HTTP Extension Framework scope (REQUIRED)\n MX: 2 Maximum wait time in seconds (REQUIRED)\n ST: upnp:rootdevice Search target (REQUIRED)\n ------------------------------------------------------------------------","docstring_tokens":["Example","M","-","SEARCH","header",":","------------------------------------------------------------------------","M","-","SEARCH","*","HTTP","\/","1",".","1","SSDP","method","for","search","requests","HOST",":","239",".","255",".","255",".","250",":","1900","SSDP","multicast","address","and","port","(","REQUIRED",")","MAN",":","ssdp",":","discover","HTTP","Extension","Framework","scope","(","REQUIRED",")","MX",":","2","Maximum","wait","time","in","seconds","(","REQUIRED",")","ST",":","upnp",":","rootdevice","Search","target","(","REQUIRED",")","------------------------------------------------------------------------"],"function":"def __init__(self, **headers):\n \"\"\"\n Example M-SEARCH header:\n ------------------------------------------------------------------------\n M-SEARCH * HTTP\/1.1 SSDP method for search requests\n HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED)\n MAN: \"ssdp:discover\" HTTP Extension Framework scope (REQUIRED)\n MX: 2 Maximum wait time in seconds (REQUIRED)\n ST: upnp:rootdevice Search target (REQUIRED)\n ------------------------------------------------------------------------\n \"\"\"\n self.headers = {}\n self.set_headers(**headers)\n\n self._available_methods = ['M-SEARCH']\n\n self.method = None\n self.host = self.headers.get('HOST')\n self.man = self.headers.get('MAN')\n self.mx = self.headers.get('MX')\n self.st = self.headers.get('ST')","function_tokens":["def","__init__","(","self",",","*","*","headers",")",":","self",".","headers","=","{","}","self",".","set_headers","(","*","*","headers",")","self",".","_available_methods","=","[","'M-SEARCH'","]","self",".","method","=","None","self",".","host","=","self",".","headers",".","get","(","'HOST'",")","self",".","man","=","self",".","headers",".","get","(","'MAN'",")","self",".","mx","=","self",".","headers",".","get","(","'MX'",")","self",".","st","=","self",".","headers",".","get","(","'ST'",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L202-L222"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"SSDPRequest.m_search","parameters":"(self, discover_delay=2, st='ssdp:all', **headers)","argument_list":"","return_statement":"","docstring":"Perform an M-SEARCH SSDP request\n\n Send an SSDP M-SEARCH request for finding UPnP devices on the network.\n\n :param discover_delay: Device discovery delay in seconds\n :type discover_delay: int\n :param st: Specify device Search Target\n :type st: str\n :param headers: Specify M-SEARCH specific headers\n :type headers: str\n :return: List of device that replied\n :rtype: list","docstring_summary":"Perform an M-SEARCH SSDP request","docstring_tokens":["Perform","an","M","-","SEARCH","SSDP","request"],"function":"def m_search(self, discover_delay=2, st='ssdp:all', **headers):\n \"\"\"Perform an M-SEARCH SSDP request\n\n Send an SSDP M-SEARCH request for finding UPnP devices on the network.\n\n :param discover_delay: Device discovery delay in seconds\n :type discover_delay: int\n :param st: Specify device Search Target\n :type st: str\n :param headers: Specify M-SEARCH specific headers\n :type headers: str\n :return: List of device that replied\n :rtype: list\n\n \"\"\"\n self.set_method('M-SEARCH')\n\n self.set_header('MAN', '\"ssdp:discover\"')\n self.set_header('MX', discover_delay)\n self.set_header('ST', st)\n self.set_headers(**headers)\n\n self.socket.settimeout(discover_delay)\n\n devices = self._send_request(self._get_raw_request())\n\n for device in devices:\n yield device","function_tokens":["def","m_search","(","self",",","discover_delay","=","2",",","st","=","'ssdp:all'",",","*","*","headers",")",":","self",".","set_method","(","'M-SEARCH'",")","self",".","set_header","(","'MAN'",",","'\"ssdp:discover\"'",")","self",".","set_header","(","'MX'",",","discover_delay",")","self",".","set_header","(","'ST'",",","st",")","self",".","set_headers","(","*","*","headers",")","self",".","socket",".","settimeout","(","discover_delay",")","devices","=","self",".","_send_request","(","self",".","_get_raw_request","(",")",")","for","device","in","devices",":","yield","device"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L297-L324"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"SSDPRequest._get_raw_request","parameters":"(self)","argument_list":"","return_statement":"return final_request_data","docstring":"Get raw request data to send to server","docstring_summary":"Get raw request data to send to server","docstring_tokens":["Get","raw","request","data","to","send","to","server"],"function":"def _get_raw_request(self):\n \"\"\"Get raw request data to send to server\"\"\"\n\n final_request_data = ''\n\n if self.method is not None:\n ssdp_start_line = '{} * HTTP\/1.1'.format(self.method)\n else:\n ssdp_start_line = 'HTTP\/1.1 200 OK'\n\n final_request_data += '{}\\r\\n'.format(ssdp_start_line)\n\n for header, value in self.headers.items():\n final_request_data += '{}: {}\\r\\n'.format(header, value)\n\n final_request_data += '\\r\\n'\n\n return final_request_data","function_tokens":["def","_get_raw_request","(","self",")",":","final_request_data","=","''","if","self",".","method","is","not","None",":","ssdp_start_line","=","'{} * HTTP\/1.1'",".","format","(","self",".","method",")","else",":","ssdp_start_line","=","'HTTP\/1.1 200 OK'","final_request_data","+=","'{}\\r\\n'",".","format","(","ssdp_start_line",")","for","header",",","value","in","self",".","headers",".","items","(",")",":","final_request_data","+=","'{}: {}\\r\\n'",".","format","(","header",",","value",")","final_request_data","+=","'\\r\\n'","return","final_request_data"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L326-L343"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/upnp.py","language":"python","identifier":"UPnP.discover","parameters":"(self, delay=2, **headers)","argument_list":"","return_statement":"return self.discovered_devices","docstring":"Find UPnP devices on the network\n\n Find available UPnP devices on the network by sending an M-SEARCH\n request.\n\n :param delay: Discovery delay, amount of time in seconds to wait for a\n reply from devices\n :type delay: int\n :param headers: Optional headers for the request\n :return: List of discovered devices\n :rtype: list","docstring_summary":"Find UPnP devices on the network","docstring_tokens":["Find","UPnP","devices","on","the","network"],"function":"def discover(self, delay=2, **headers):\n \"\"\"Find UPnP devices on the network\n\n Find available UPnP devices on the network by sending an M-SEARCH\n request.\n\n :param delay: Discovery delay, amount of time in seconds to wait for a\n reply from devices\n :type delay: int\n :param headers: Optional headers for the request\n :return: List of discovered devices\n :rtype: list\n\n \"\"\"\n\n discovered_devices = []\n for device in self.ssdp.m_search(discover_delay=delay,\n st='upnp:rootdevice',\n **headers):\n discovered_devices.append(device)\n\n self.discovered_devices = discovered_devices\n return self.discovered_devices","function_tokens":["def","discover","(","self",",","delay","=","2",",","*","*","headers",")",":","discovered_devices","=","[","]","for","device","in","self",".","ssdp",".","m_search","(","discover_delay","=","delay",",","st","=","'upnp:rootdevice'",",","*","*","headers",")",":","discovered_devices",".","append","(","device",")","self",".","discovered_devices","=","discovered_devices","return","self",".","discovered_devices"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/upnp.py#L379-L401"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_satellite","parameters":"()","argument_list":"","return_statement":"return sat","docstring":"Configure satellite covering the user","docstring_summary":"Configure satellite covering the user","docstring_tokens":["Configure","satellite","covering","the","user"],"function":"def _cfg_satellite():\n \"\"\"Configure satellite covering the user\"\"\"\n os.system('clear')\n util.print_header(\"Satellite\")\n\n help_msg = \"Not sure? Check the coverage map at:\\n\" \\\n \"https:\/\/blockstream.com\/satellite\/#satellite_network-coverage\"\n\n question = \"Which satellite below covers your location?\"\n sat = util.ask_multiple_choice(\n defs.satellites, question, \"Satellite\",\n lambda sat: '{} ({})'.format(sat['name'], sat['alias']), help_msg)\n return sat","function_tokens":["def","_cfg_satellite","(",")",":","os",".","system","(","'clear'",")","util",".","print_header","(","\"Satellite\"",")","help_msg","=","\"Not sure? Check the coverage map at:\\n\"","\"https:\/\/blockstream.com\/satellite\/#satellite_network-coverage\"","question","=","\"Which satellite below covers your location?\"","sat","=","util",".","ask_multiple_choice","(","defs",".","satellites",",","question",",","\"Satellite\"",",","lambda","sat",":","'{} ({})'",".","format","(","sat","[","'name'","]",",","sat","[","'alias'","]",")",",","help_msg",")","return","sat"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L17-L29"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_get_rx_marketing_name","parameters":"(rx)","argument_list":"","return_statement":"return model","docstring":"Get the marketed receiver name (including satellite kit name)","docstring_summary":"Get the marketed receiver name (including satellite kit name)","docstring_tokens":["Get","the","marketed","receiver","name","(","including","satellite","kit","name",")"],"function":"def _get_rx_marketing_name(rx):\n \"\"\"Get the marketed receiver name (including satellite kit name)\"\"\"\n model = (rx['vendor'] + \" \" + rx['model']).strip()\n if model == \"Novra S400\":\n model += \" (pro kit)\" # append\n elif model == \"TBS 5927\":\n model += \" (basic kit)\" # append\n elif model == \"Selfsat IP22\":\n model = \"Blockstream Base Station\" # overwrite\n elif model == \"RTL-SDR\":\n model += \" software-defined\"\n return model","function_tokens":["def","_get_rx_marketing_name","(","rx",")",":","model","=","(","rx","[","'vendor'","]","+","\" \"","+","rx","[","'model'","]",")",".","strip","(",")","if","model","==","\"Novra S400\"",":","model","+=","\" (pro kit)\"","# append","elif","model","==","\"TBS 5927\"",":","model","+=","\" (basic kit)\"","# append","elif","model","==","\"Selfsat IP22\"",":","model","=","\"Blockstream Base Station\"","# overwrite","elif","model","==","\"RTL-SDR\"",":","model","+=","\" software-defined\"","return","model"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L32-L43"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_get_antenna_name","parameters":"(x)","argument_list":"","return_statement":"return s","docstring":"Get antenna name for the configuration menu","docstring_summary":"Get antenna name for the configuration menu","docstring_tokens":["Get","antenna","name","for","the","configuration","menu"],"function":"def _get_antenna_name(x):\n \"\"\"Get antenna name for the configuration menu\"\"\"\n if x['type'] == 'dish':\n s = 'Satellite Dish ({})'.format(x['label'])\n elif x['type'] == 'sat-ip':\n s = 'Blockstream Base Station (Legacy Output)'\n else:\n s = 'Blockstream Flat-Panel Antenna'\n return s","function_tokens":["def","_get_antenna_name","(","x",")",":","if","x","[","'type'","]","==","'dish'",":","s","=","'Satellite Dish ({})'",".","format","(","x","[","'label'","]",")","elif","x","[","'type'","]","==","'sat-ip'",":","s","=","'Blockstream Base Station (Legacy Output)'","else",":","s","=","'Blockstream Flat-Panel Antenna'","return","s"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L46-L54"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_ask_antenna","parameters":"()","argument_list":"","return_statement":"return antenna","docstring":"Configure antenna","docstring_summary":"Configure antenna","docstring_tokens":["Configure","antenna"],"function":"def _ask_antenna():\n \"\"\"Configure antenna\"\"\"\n os.system('clear')\n util.print_header(\"Antenna\")\n\n question = \"What kind of antenna are you using?\"\n antenna = util.ask_multiple_choice(defs.antennas,\n question,\n \"Antenna\",\n _get_antenna_name,\n none_option=True,\n none_str=\"Other\")\n\n if (antenna is None):\n size = util.typed_input(\"Enter size in cm\",\n \"Please enter an integer number in cm\",\n in_type=int)\n antenna = {'label': \"custom\", 'type': 'dish', 'size': size}\n\n return antenna","function_tokens":["def","_ask_antenna","(",")",":","os",".","system","(","'clear'",")","util",".","print_header","(","\"Antenna\"",")","question","=","\"What kind of antenna are you using?\"","antenna","=","util",".","ask_multiple_choice","(","defs",".","antennas",",","question",",","\"Antenna\"",",","_get_antenna_name",",","none_option","=","True",",","none_str","=","\"Other\"",")","if","(","antenna","is","None",")",":","size","=","util",".","typed_input","(","\"Enter size in cm\"",",","\"Please enter an integer number in cm\"",",","in_type","=","int",")","antenna","=","{","'label'",":","\"custom\"",",","'type'",":","'dish'",",","'size'",":","size","}","return","antenna"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L57-L76"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_rx_setup","parameters":"()","argument_list":"","return_statement":"return setup","docstring":"Configure Rx setup - which receiver user is using","docstring_summary":"Configure Rx setup - which receiver user is using","docstring_tokens":["Configure","Rx","setup","-","which","receiver","user","is","using"],"function":"def _cfg_rx_setup():\n \"\"\"Configure Rx setup - which receiver user is using \"\"\"\n os.system('clear')\n util.print_header(\"Receiver\")\n\n # Receiver\n question = \"Select your DVB-S2 receiver:\"\n setup = util.ask_multiple_choice(\n defs.demods, question, \"Receiver\",\n lambda x: '{} receiver'.format(_get_rx_marketing_name(x)))\n\n # Network interface connected to the standalone receiver\n if (setup['type'] == defs.standalone_setup_type):\n try:\n devices = os.listdir('\/sys\/class\/net\/')\n except FileNotFoundError:\n devices = None\n pass\n\n question = \"Which network interface is connected to the receiver?\"\n if (devices is not None):\n netdev = util.ask_multiple_choice(devices, question, \"Interface\",\n lambda x: '{}'.format(x))\n else:\n netdev = input(question + \" \")\n\n setup['netdev'] = netdev.strip()\n\n custom_ip = util.ask_yes_or_no(\n \"Have you manually assigned a custom IP address to the receiver?\",\n default=\"n\")\n if (custom_ip):\n ipv4_addr = util.typed_input(\"Which IPv4 address?\",\n in_type=IPv4Address)\n setup[\"rx_ip\"] = str(ipv4_addr)\n else:\n setup[\"rx_ip\"] = defs.default_standalone_ip_addr\n\n # Define the Sat-IP antenna directly without asking the user\n if (setup['type'] == defs.sat_ip_setup_type):\n # NOTE: this works as long as there is a single Sat-IP antenna in the\n # list. In the future, if other Sat-IP antennas are included, change to\n # a multiple-choice prompt.\n for antenna in defs.antennas:\n if antenna['type'] == 'sat-ip':\n setup['antenna'] = antenna\n return setup\n # We should have returned in the preceding line.\n raise RuntimeError(\"Failed to find antenna of {} receiver\".format(\n defs.sat_ip_setup_type))\n\n # Antenna\n setup['antenna'] = _ask_antenna()\n\n return setup","function_tokens":["def","_cfg_rx_setup","(",")",":","os",".","system","(","'clear'",")","util",".","print_header","(","\"Receiver\"",")","# Receiver","question","=","\"Select your DVB-S2 receiver:\"","setup","=","util",".","ask_multiple_choice","(","defs",".","demods",",","question",",","\"Receiver\"",",","lambda","x",":","'{} receiver'",".","format","(","_get_rx_marketing_name","(","x",")",")",")","# Network interface connected to the standalone receiver","if","(","setup","[","'type'","]","==","defs",".","standalone_setup_type",")",":","try",":","devices","=","os",".","listdir","(","'\/sys\/class\/net\/'",")","except","FileNotFoundError",":","devices","=","None","pass","question","=","\"Which network interface is connected to the receiver?\"","if","(","devices","is","not","None",")",":","netdev","=","util",".","ask_multiple_choice","(","devices",",","question",",","\"Interface\"",",","lambda","x",":","'{}'",".","format","(","x",")",")","else",":","netdev","=","input","(","question","+","\" \"",")","setup","[","'netdev'","]","=","netdev",".","strip","(",")","custom_ip","=","util",".","ask_yes_or_no","(","\"Have you manually assigned a custom IP address to the receiver?\"",",","default","=","\"n\"",")","if","(","custom_ip",")",":","ipv4_addr","=","util",".","typed_input","(","\"Which IPv4 address?\"",",","in_type","=","IPv4Address",")","setup","[","\"rx_ip\"","]","=","str","(","ipv4_addr",")","else",":","setup","[","\"rx_ip\"","]","=","defs",".","default_standalone_ip_addr","# Define the Sat-IP antenna directly without asking the user","if","(","setup","[","'type'","]","==","defs",".","sat_ip_setup_type",")",":","# NOTE: this works as long as there is a single Sat-IP antenna in the","# list. In the future, if other Sat-IP antennas are included, change to","# a multiple-choice prompt.","for","antenna","in","defs",".","antennas",":","if","antenna","[","'type'","]","==","'sat-ip'",":","setup","[","'antenna'","]","=","antenna","return","setup","# We should have returned in the preceding line.","raise","RuntimeError","(","\"Failed to find antenna of {} receiver\"",".","format","(","defs",".","sat_ip_setup_type",")",")","# Antenna","setup","[","'antenna'","]","=","_ask_antenna","(",")","return","setup"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L79-L133"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_ask_lnb_freq_range","parameters":"()","argument_list":"","return_statement":"return in_range","docstring":"Prompt the user for the LNB's input frequency range","docstring_summary":"Prompt the user for the LNB's input frequency range","docstring_tokens":["Prompt","the","user","for","the","LNB","s","input","frequency","range"],"function":"def _ask_lnb_freq_range():\n \"\"\"Prompt the user for the LNB's input frequency range\"\"\"\n in_range = []\n while (True):\n while (len(in_range) != 2):\n try:\n resp = input(\n \"Inform the two extreme frequencies (in MHz) of \"\n \"your LNB's frequency range, separated by comma: \")\n in_range = [float(x) for x in resp.split(\",\")]\n except ValueError:\n continue\n\n if (in_range[1] < in_range[0]):\n in_range = []\n print(\"Please, provide the lowest frequency first, followed by \"\n \"the highest.\")\n continue\n\n if (in_range[0] < 3000 or in_range[1] < 3000):\n in_range = []\n print(\"Please, provide the frequencies in MHz.\")\n continue\n\n break\n\n return in_range","function_tokens":["def","_ask_lnb_freq_range","(",")",":","in_range","=","[","]","while","(","True",")",":","while","(","len","(","in_range",")","!=","2",")",":","try",":","resp","=","input","(","\"Inform the two extreme frequencies (in MHz) of \"","\"your LNB's frequency range, separated by comma: \"",")","in_range","=","[","float","(","x",")","for","x","in","resp",".","split","(","\",\"",")","]","except","ValueError",":","continue","if","(","in_range","[","1","]","<","in_range","[","0","]",")",":","in_range","=","[","]","print","(","\"Please, provide the lowest frequency first, followed by \"","\"the highest.\"",")","continue","if","(","in_range","[","0","]","<","3000","or","in_range","[","1","]","<","3000",")",":","in_range","=","[","]","print","(","\"Please, provide the frequencies in MHz.\"",")","continue","break","return","in_range"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L136-L162"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_ask_lnb_lo","parameters":"(single_lo=True)","argument_list":"","return_statement":"return lo_freq","docstring":"Prompt the user for the LNB's LO frequencies","docstring_summary":"Prompt the user for the LNB's LO frequencies","docstring_tokens":["Prompt","the","user","for","the","LNB","s","LO","frequencies"],"function":"def _ask_lnb_lo(single_lo=True):\n \"\"\"Prompt the user for the LNB's LO frequencies\"\"\"\n if (single_lo):\n while (True):\n lo_freq = util.typed_input(\"LNB LO frequency in MHz\",\n in_type=float)\n\n if (lo_freq < 3000):\n print(\"Please, provide the frequencies in MHz.\")\n continue\n\n break\n return lo_freq\n\n lo_freq = []\n while (True):\n while (len(lo_freq) != 2):\n try:\n resp = input(\"Inform the two LO frequencies in MHz, separated \"\n \"by comma: \")\n lo_freq = [float(x) for x in resp.split(\",\")]\n except ValueError:\n continue\n\n if (lo_freq[1] < lo_freq[0]):\n lo_freq = []\n print(\"Please, provide the low LO frequency first, followed by \"\n \"the high LO frequency.\")\n continue\n\n if (lo_freq[0] < 3000 or lo_freq[1] < 3000):\n lo_freq = []\n print(\"Please, provide the frequencies in MHz.\")\n continue\n\n break\n\n return lo_freq","function_tokens":["def","_ask_lnb_lo","(","single_lo","=","True",")",":","if","(","single_lo",")",":","while","(","True",")",":","lo_freq","=","util",".","typed_input","(","\"LNB LO frequency in MHz\"",",","in_type","=","float",")","if","(","lo_freq","<","3000",")",":","print","(","\"Please, provide the frequencies in MHz.\"",")","continue","break","return","lo_freq","lo_freq","=","[","]","while","(","True",")",":","while","(","len","(","lo_freq",")","!=","2",")",":","try",":","resp","=","input","(","\"Inform the two LO frequencies in MHz, separated \"","\"by comma: \"",")","lo_freq","=","[","float","(","x",")","for","x","in","resp",".","split","(","\",\"",")","]","except","ValueError",":","continue","if","(","lo_freq","[","1","]","<","lo_freq","[","0","]",")",":","lo_freq","=","[","]","print","(","\"Please, provide the low LO frequency first, followed by \"","\"the high LO frequency.\"",")","continue","if","(","lo_freq","[","0","]","<","3000","or","lo_freq","[","1","]","<","3000",")",":","lo_freq","=","[","]","print","(","\"Please, provide the frequencies in MHz.\"",")","continue","break","return","lo_freq"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L165-L202"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_custom_lnb","parameters":"(sat)","argument_list":"","return_statement":"return {\n 'vendor': \"\",\n 'model': \"\",\n 'in_range': custom_lnb_in_range,\n 'lo_freq': custom_lnb_lo_freq,\n 'universal': custom_lnb_universal,\n 'band': custom_lnb_band,\n 'pol': pol['id']\n }","docstring":"Configure custom LNB based on user-entered specs\n\n Args:\n sat : user's satellite info","docstring_summary":"Configure custom LNB based on user-entered specs","docstring_tokens":["Configure","custom","LNB","based","on","user","-","entered","specs"],"function":"def _cfg_custom_lnb(sat):\n \"\"\"Configure custom LNB based on user-entered specs\n\n Args:\n sat : user's satellite info\n\n \"\"\"\n\n print(\"\\nPlease, inform the specifications of your LNB:\")\n\n bands = [\"C\", \"Ku\"]\n question = \"Frequency band:\"\n custom_lnb_band = util.ask_multiple_choice(bands, question, \"Band\",\n lambda x: '{}'.format(x))\n\n if (sat['band'].lower() != custom_lnb_band.lower()):\n logging.error(\"You must use a %s band LNB to receive from %s\" %\n (sat['band'], sat['name']))\n sys.exit(1)\n\n if (custom_lnb_band == \"Ku\"):\n custom_lnb_universal = util.ask_yes_or_no(\n \"Is it a Universal Ku band LNB?\")\n\n if (custom_lnb_universal):\n # Input frequency range\n print()\n util.fill_print(\"\"\"A Universal Ku band LNB typically covers an\n input frequency range from 10.7 to 12.75 GHz.\"\"\")\n if (util.ask_yes_or_no(\"Does your LNB cover this input range \"\n \"from 10.7 to 12.75 GHz?\")):\n custom_lnb_in_range = [10700.0, 12750.0]\n else:\n custom_lnb_in_range = _ask_lnb_freq_range()\n\n # LO\n print()\n util.fill_print(\"\"\"A Universal Ku band LNB has two LO (local\n oscillator) frequencies. Typically the two frequencies are 9750\n MHz and 10600 MHz.\"\"\")\n if (util.ask_yes_or_no(\"Does your LNB have LO frequencies 9750 \"\n \"MHz and 10600 MHz?\")):\n custom_lnb_lo_freq = [9750.0, 10600.0]\n else:\n custom_lnb_lo_freq = _ask_lnb_lo(single_lo=False)\n else:\n # Non-universal Ku-band LNB\n custom_lnb_in_range = _ask_lnb_freq_range()\n custom_lnb_lo_freq = _ask_lnb_lo()\n else:\n # C-band LNB\n custom_lnb_universal = False\n custom_lnb_in_range = _ask_lnb_freq_range()\n custom_lnb_lo_freq = _ask_lnb_lo()\n\n # Polarization\n question = \"Choose the LNB polarization:\"\n options = [{\n 'id': \"Dual\",\n 'text': \"Dual polarization (horizontal and vertical)\"\n }, {\n 'id': \"H\",\n 'text': \"Horizontal\"\n }, {\n 'id': \"V\",\n 'text': \"Vertical\"\n }]\n pol = util.ask_multiple_choice(options, question, \"Polarization\",\n lambda x: '{}'.format(x['text']))\n\n return {\n 'vendor': \"\",\n 'model': \"\",\n 'in_range': custom_lnb_in_range,\n 'lo_freq': custom_lnb_lo_freq,\n 'universal': custom_lnb_universal,\n 'band': custom_lnb_band,\n 'pol': pol['id']\n }","function_tokens":["def","_cfg_custom_lnb","(","sat",")",":","print","(","\"\\nPlease, inform the specifications of your LNB:\"",")","bands","=","[","\"C\"",",","\"Ku\"","]","question","=","\"Frequency band:\"","custom_lnb_band","=","util",".","ask_multiple_choice","(","bands",",","question",",","\"Band\"",",","lambda","x",":","'{}'",".","format","(","x",")",")","if","(","sat","[","'band'","]",".","lower","(",")","!=","custom_lnb_band",".","lower","(",")",")",":","logging",".","error","(","\"You must use a %s band LNB to receive from %s\"","%","(","sat","[","'band'","]",",","sat","[","'name'","]",")",")","sys",".","exit","(","1",")","if","(","custom_lnb_band","==","\"Ku\"",")",":","custom_lnb_universal","=","util",".","ask_yes_or_no","(","\"Is it a Universal Ku band LNB?\"",")","if","(","custom_lnb_universal",")",":","# Input frequency range","print","(",")","util",".","fill_print","(","\"\"\"A Universal Ku band LNB typically covers an\n input frequency range from 10.7 to 12.75 GHz.\"\"\"",")","if","(","util",".","ask_yes_or_no","(","\"Does your LNB cover this input range \"","\"from 10.7 to 12.75 GHz?\"",")",")",":","custom_lnb_in_range","=","[","10700.0",",","12750.0","]","else",":","custom_lnb_in_range","=","_ask_lnb_freq_range","(",")","# LO","print","(",")","util",".","fill_print","(","\"\"\"A Universal Ku band LNB has two LO (local\n oscillator) frequencies. Typically the two frequencies are 9750\n MHz and 10600 MHz.\"\"\"",")","if","(","util",".","ask_yes_or_no","(","\"Does your LNB have LO frequencies 9750 \"","\"MHz and 10600 MHz?\"",")",")",":","custom_lnb_lo_freq","=","[","9750.0",",","10600.0","]","else",":","custom_lnb_lo_freq","=","_ask_lnb_lo","(","single_lo","=","False",")","else",":","# Non-universal Ku-band LNB","custom_lnb_in_range","=","_ask_lnb_freq_range","(",")","custom_lnb_lo_freq","=","_ask_lnb_lo","(",")","else",":","# C-band LNB","custom_lnb_universal","=","False","custom_lnb_in_range","=","_ask_lnb_freq_range","(",")","custom_lnb_lo_freq","=","_ask_lnb_lo","(",")","# Polarization","question","=","\"Choose the LNB polarization:\"","options","=","[","{","'id'",":","\"Dual\"",",","'text'",":","\"Dual polarization (horizontal and vertical)\"","}",",","{","'id'",":","\"H\"",",","'text'",":","\"Horizontal\"","}",",","{","'id'",":","\"V\"",",","'text'",":","\"Vertical\"","}","]","pol","=","util",".","ask_multiple_choice","(","options",",","question",",","\"Polarization\"",",","lambda","x",":","'{}'",".","format","(","x","[","'text'","]",")",")","return","{","'vendor'",":","\"\"",",","'model'",":","\"\"",",","'in_range'",":","custom_lnb_in_range",",","'lo_freq'",":","custom_lnb_lo_freq",",","'universal'",":","custom_lnb_universal",",","'band'",":","custom_lnb_band",",","'pol'",":","pol","[","'id'","]","}"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L205-L283"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_sat_freq_in_lnb_range","parameters":"(sat, lnb)","argument_list":"","return_statement":"return sat['dl_freq'] > lnb['in_range'][0] and \\\n sat['dl_freq'] < lnb['in_range'][1]","docstring":"Check if the satellite signal is within the LNB input range","docstring_summary":"Check if the satellite signal is within the LNB input range","docstring_tokens":["Check","if","the","satellite","signal","is","within","the","LNB","input","range"],"function":"def _sat_freq_in_lnb_range(sat, lnb):\n \"\"\"Check if the satellite signal is within the LNB input range\"\"\"\n return sat['dl_freq'] > lnb['in_range'][0] and \\\n sat['dl_freq'] < lnb['in_range'][1]","function_tokens":["def","_sat_freq_in_lnb_range","(","sat",",","lnb",")",":","return","sat","[","'dl_freq'","]",">","lnb","[","'in_range'","]","[","0","]","and","sat","[","'dl_freq'","]","<","lnb","[","'in_range'","]","[","1","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L286-L289"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_ask_lnb","parameters":"(sat)","argument_list":"","return_statement":"return lnb","docstring":"Ask the user's LNB","docstring_summary":"Ask the user's LNB","docstring_tokens":["Ask","the","user","s","LNB"],"function":"def _ask_lnb(sat):\n \"\"\"Ask the user's LNB\"\"\"\n question = \"Please, inform your LNB model:\"\n lnb_options = [\n lnb for lnb in defs.lnbs\n if _sat_freq_in_lnb_range(sat, lnb) and lnb['vendor'] != 'Selfsat'\n ]\n lnb = util.ask_multiple_choice(\n lnb_options,\n question,\n \"LNB\",\n lambda x: \"{} {} {}\".format(\n x['vendor'], x['model'], \"(Universal Ku band LNBF)\"\n if x['universal'] else \"\"),\n none_option=True,\n none_str=\"Other\")\n\n if (lnb is None):\n lnb = _cfg_custom_lnb(sat)\n\n return lnb","function_tokens":["def","_ask_lnb","(","sat",")",":","question","=","\"Please, inform your LNB model:\"","lnb_options","=","[","lnb","for","lnb","in","defs",".","lnbs","if","_sat_freq_in_lnb_range","(","sat",",","lnb",")","and","lnb","[","'vendor'","]","!=","'Selfsat'","]","lnb","=","util",".","ask_multiple_choice","(","lnb_options",",","question",",","\"LNB\"",",","lambda","x",":","\"{} {} {}\"",".","format","(","x","[","'vendor'","]",",","x","[","'model'","]",",","\"(Universal Ku band LNBF)\"","if","x","[","'universal'","]","else","\"\"",")",",","none_option","=","True",",","none_str","=","\"Other\"",")","if","(","lnb","is","None",")",":","lnb","=","_cfg_custom_lnb","(","sat",")","return","lnb"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L292-L312"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_ask_psu_voltage","parameters":"(question)","argument_list":"","return_statement":"return voltage","docstring":"Prompt for the power inserter model or voltage","docstring_summary":"Prompt for the power inserter model or voltage","docstring_tokens":["Prompt","for","the","power","inserter","model","or","voltage"],"function":"def _ask_psu_voltage(question):\n \"\"\"Prompt for the power inserter model or voltage\"\"\"\n psu = util.ask_multiple_choice(defs.psus,\n question,\n \"Power inserter\",\n lambda x: \"{}\".format(x['model']),\n none_option=True,\n none_str=\"No - another model\")\n if (psu is None):\n voltage = util.typed_input(\"What is the voltage supplied to the \"\n \"LNB by your power inserter?\")\n else:\n voltage = psu[\"voltage\"]\n\n return voltage","function_tokens":["def","_ask_psu_voltage","(","question",")",":","psu","=","util",".","ask_multiple_choice","(","defs",".","psus",",","question",",","\"Power inserter\"",",","lambda","x",":","\"{}\"",".","format","(","x","[","'model'","]",")",",","none_option","=","True",",","none_str","=","\"No - another model\"",")","if","(","psu","is","None",")",":","voltage","=","util",".","typed_input","(","\"What is the voltage supplied to the \"","\"LNB by your power inserter?\"",")","else",":","voltage","=","psu","[","\"voltage\"","]","return","voltage"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L315-L329"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_lnb","parameters":"(sat, setup)","argument_list":"","return_statement":"return lnb","docstring":"Configure LNB - either from preset or from custom specs\n\n Configure also the LNB power supply, if applicable.\n\n Args:\n sat : user's satellite info\n setup : user's setup info","docstring_summary":"Configure LNB - either from preset or from custom specs","docstring_tokens":["Configure","LNB","-","either","from","preset","or","from","custom","specs"],"function":"def _cfg_lnb(sat, setup):\n \"\"\"Configure LNB - either from preset or from custom specs\n\n Configure also the LNB power supply, if applicable.\n\n Args:\n sat : user's satellite info\n setup : user's setup info\n\n \"\"\"\n\n # For flat-panel and Sat-IP antennas, the LNB is the integrated one\n if (setup['antenna']['type'] in ['flat', 'sat-ip']):\n for lnb in defs.lnbs:\n if lnb['vendor'] == 'Selfsat':\n lnb[\"v1_pointed\"] = False\n return lnb\n\n os.system('clear')\n util.print_header(\"LNB\")\n\n lnb = _ask_lnb(sat)\n\n if (not _sat_freq_in_lnb_range(sat, lnb)):\n logging.warning(\"Your LNB's input frequency range does not cover the \"\n \"frequency of {} ({} MHz)\".format(\n sat['name'], sat['dl_freq']))\n if not util.ask_yes_or_no(\"Continue anyway?\", default=\"n\"):\n logging.error(\"Invalid LNB\")\n sys.exit(1)\n\n if (sat['band'].lower() != lnb['band'].lower()):\n logging.error(\"The LNB you chose cannot operate \" +\n \"in %s band (band of satellite %s)\" %\n (sat['band'], sat['alias']))\n sys.exit(1)\n\n # When configuring a non-SDR receiver with a dual polarization LNB, we must\n # know whether the LNB was pointed before on an SDR setup in order to\n # define the polarization on channels.conf. When configuring an SDR\n # receiver, collect the power inserter voltage too for future use.\n if ((lnb['pol'].lower() == \"dual\" and setup['type'] != defs.sdr_setup_type)\n or setup['type'] == defs.sdr_setup_type):\n os.system('clear')\n util.print_header(\"Power Supply\")\n\n if (lnb['pol'].lower() == \"dual\" and setup['type'] != defs.sdr_setup_type):\n prev_sdr_setup = util.ask_yes_or_no(\n \"Are you reusing an LNB that is already pointed and that was used \"\n \"before by an SDR receiver?\",\n default='n',\n help_msg=\"NOTE: this information is helpful to determine the \"\n \"polarization required for the LNB.\")\n\n lnb[\"v1_pointed\"] = prev_sdr_setup\n\n if (prev_sdr_setup):\n print()\n question = (\n \"In the pre-existing SDR setup, did you use one of the \"\n \"LNB power inserters below?\")\n lnb[\"v1_psu_voltage\"] = _ask_psu_voltage(question)\n elif (setup['type'] == defs.sdr_setup_type):\n question = (\"Are you using one of the LNB power inserters below?\")\n lnb[\"psu_voltage\"] = _ask_psu_voltage(question)\n\n return lnb","function_tokens":["def","_cfg_lnb","(","sat",",","setup",")",":","# For flat-panel and Sat-IP antennas, the LNB is the integrated one","if","(","setup","[","'antenna'","]","[","'type'","]","in","[","'flat'",",","'sat-ip'","]",")",":","for","lnb","in","defs",".","lnbs",":","if","lnb","[","'vendor'","]","==","'Selfsat'",":","lnb","[","\"v1_pointed\"","]","=","False","return","lnb","os",".","system","(","'clear'",")","util",".","print_header","(","\"LNB\"",")","lnb","=","_ask_lnb","(","sat",")","if","(","not","_sat_freq_in_lnb_range","(","sat",",","lnb",")",")",":","logging",".","warning","(","\"Your LNB's input frequency range does not cover the \"","\"frequency of {} ({} MHz)\"",".","format","(","sat","[","'name'","]",",","sat","[","'dl_freq'","]",")",")","if","not","util",".","ask_yes_or_no","(","\"Continue anyway?\"",",","default","=","\"n\"",")",":","logging",".","error","(","\"Invalid LNB\"",")","sys",".","exit","(","1",")","if","(","sat","[","'band'","]",".","lower","(",")","!=","lnb","[","'band'","]",".","lower","(",")",")",":","logging",".","error","(","\"The LNB you chose cannot operate \"","+","\"in %s band (band of satellite %s)\"","%","(","sat","[","'band'","]",",","sat","[","'alias'","]",")",")","sys",".","exit","(","1",")","# When configuring a non-SDR receiver with a dual polarization LNB, we must","# know whether the LNB was pointed before on an SDR setup in order to","# define the polarization on channels.conf. When configuring an SDR","# receiver, collect the power inserter voltage too for future use.","if","(","(","lnb","[","'pol'","]",".","lower","(",")","==","\"dual\"","and","setup","[","'type'","]","!=","defs",".","sdr_setup_type",")","or","setup","[","'type'","]","==","defs",".","sdr_setup_type",")",":","os",".","system","(","'clear'",")","util",".","print_header","(","\"Power Supply\"",")","if","(","lnb","[","'pol'","]",".","lower","(",")","==","\"dual\"","and","setup","[","'type'","]","!=","defs",".","sdr_setup_type",")",":","prev_sdr_setup","=","util",".","ask_yes_or_no","(","\"Are you reusing an LNB that is already pointed and that was used \"","\"before by an SDR receiver?\"",",","default","=","'n'",",","help_msg","=","\"NOTE: this information is helpful to determine the \"","\"polarization required for the LNB.\"",")","lnb","[","\"v1_pointed\"","]","=","prev_sdr_setup","if","(","prev_sdr_setup",")",":","print","(",")","question","=","(","\"In the pre-existing SDR setup, did you use one of the \"","\"LNB power inserters below?\"",")","lnb","[","\"v1_psu_voltage\"","]","=","_ask_psu_voltage","(","question",")","elif","(","setup","[","'type'","]","==","defs",".","sdr_setup_type",")",":","question","=","(","\"Are you using one of the LNB power inserters below?\"",")","lnb","[","\"psu_voltage\"","]","=","_ask_psu_voltage","(","question",")","return","lnb"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L332-L398"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_frequencies","parameters":"(sat, lnb, setup)","argument_list":"","return_statement":"return {'dl': sat['dl_freq'], 'lo': lo_freq, 'l_band': if_freq}","docstring":"Print summary of frequencies\n\n Inform the downlink RF frequency, the LNB LO frequency and the L-band\n frequency to be configured in the receiver.\n\n Args:\n sat : user's satellite info\n lnb : user's LNB info","docstring_summary":"Print summary of frequencies","docstring_tokens":["Print","summary","of","frequencies"],"function":"def _cfg_frequencies(sat, lnb, setup):\n \"\"\"Print summary of frequencies\n\n Inform the downlink RF frequency, the LNB LO frequency and the L-band\n frequency to be configured in the receiver.\n\n Args:\n sat : user's satellite info\n lnb : user's LNB info\n\n \"\"\"\n getcontext().prec = 8\n\n if (sat['band'].lower() == \"ku\"):\n if (lnb['universal']):\n assert(isinstance(lnb['lo_freq'], list)), \\\n \"A Universal LNB must have a list with two LO frequencies\"\n assert(len(lnb['lo_freq']) == 2), \\\n \"A Universal LNB must have two LO frequencies\"\n\n if (sat['dl_freq'] > defs.ku_band_thresh):\n lo_freq = lnb['lo_freq'][1]\n else:\n lo_freq = lnb['lo_freq'][0]\n else:\n lo_freq = lnb['lo_freq']\n\n if_freq = float(Decimal(sat['dl_freq']) - Decimal(lo_freq))\n\n elif (sat['band'].lower() == \"c\"):\n lo_freq = lnb['lo_freq']\n if_freq = float(Decimal(lo_freq) - Decimal(sat['dl_freq']))\n else:\n raise ValueError(\"Unknown satellite band\")\n\n if (if_freq < setup['tun_range'][0] or if_freq > setup['tun_range'][1]):\n logging.error(\"Your LNB yields an L-band frequency that is out of \"\n \"the tuning range of the {} receiver.\".format(\n _get_rx_marketing_name(setup)))\n sys.exit(1)\n\n return {'dl': sat['dl_freq'], 'lo': lo_freq, 'l_band': if_freq}","function_tokens":["def","_cfg_frequencies","(","sat",",","lnb",",","setup",")",":","getcontext","(",")",".","prec","=","8","if","(","sat","[","'band'","]",".","lower","(",")","==","\"ku\"",")",":","if","(","lnb","[","'universal'","]",")",":","assert","(","isinstance","(","lnb","[","'lo_freq'","]",",","list",")",")",",","\"A Universal LNB must have a list with two LO frequencies\"","assert","(","len","(","lnb","[","'lo_freq'","]",")","==","2",")",",","\"A Universal LNB must have two LO frequencies\"","if","(","sat","[","'dl_freq'","]",">","defs",".","ku_band_thresh",")",":","lo_freq","=","lnb","[","'lo_freq'","]","[","1","]","else",":","lo_freq","=","lnb","[","'lo_freq'","]","[","0","]","else",":","lo_freq","=","lnb","[","'lo_freq'","]","if_freq","=","float","(","Decimal","(","sat","[","'dl_freq'","]",")","-","Decimal","(","lo_freq",")",")","elif","(","sat","[","'band'","]",".","lower","(",")","==","\"c\"",")",":","lo_freq","=","lnb","[","'lo_freq'","]","if_freq","=","float","(","Decimal","(","lo_freq",")","-","Decimal","(","sat","[","'dl_freq'","]",")",")","else",":","raise","ValueError","(","\"Unknown satellite band\"",")","if","(","if_freq","<","setup","[","'tun_range'","]","[","0","]","or","if_freq",">","setup","[","'tun_range'","]","[","1","]",")",":","logging",".","error","(","\"Your LNB yields an L-band frequency that is out of \"","\"the tuning range of the {} receiver.\"",".","format","(","_get_rx_marketing_name","(","setup",")",")",")","sys",".","exit","(","1",")","return","{","'dl'",":","sat","[","'dl_freq'","]",",","'lo'",":","lo_freq",",","'l_band'",":","if_freq","}"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L401-L442"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_chan_conf","parameters":"(info, chan_file)","argument_list":"","return_statement":"","docstring":"Generate the channels.conf file","docstring_summary":"Generate the channels.conf file","docstring_tokens":["Generate","the","channels",".","conf","file"],"function":"def _cfg_chan_conf(info, chan_file):\n \"\"\"Generate the channels.conf file\"\"\"\n\n util.print_header(\"Channel Configuration\")\n\n print(\n textwrap.fill(\"This step will generate the channel configuration \"\n \"file that is required when launching the USB \"\n \"receiver in Linux.\") + \"\\n\")\n\n if (os.path.isfile(chan_file)):\n print(\"Found previous %s file:\" % (chan_file))\n\n if (not util.ask_yes_or_no(\"Remove and regenerate file?\")):\n print(\"Configuration aborted.\")\n return\n else:\n os.remove(chan_file)\n\n with open(chan_file, 'w') as f:\n f.write('[blocksat-ch]\\n')\n f.write('\\tDELIVERY_SYSTEM = DVBS2\\n')\n f.write('\\tFREQUENCY = %u\\n' % (int(info['sat']['dl_freq'] * 1000)))\n if (info['lnb']['pol'].lower() == \"dual\"\n and 'v1_pointed' in info['lnb'] and info['lnb']['v1_pointed']):\n # If a dual-polarization LNB is already pointed for Blocksat v1,\n # then we must use the polarization that the LNB was pointed to\n # originally, regardless of the satellite signal's polarization. In\n # v1, what mattered the most was the power supply voltage, which\n # determined the polarization of the dual polarization LNBs. If the\n # power supply provides voltage >= 18 (often the case), then the\n # LNB necessarily operates currently with horizontal polarization.\n # Thus, on channels.conf we must use the same polarization in order\n # for the DVB adapter to supply the 18VDC voltage.\n if (info['lnb'][\"v1_psu_voltage\"] >= 16): # 16VDC threshold\n f.write('\\tPOLARIZATION = HORIZONTAL\\n')\n else:\n f.write('\\tPOLARIZATION = VERTICAL\\n')\n else:\n if (info['sat']['pol'] == 'V'):\n f.write('\\tPOLARIZATION = VERTICAL\\n')\n else:\n f.write('\\tPOLARIZATION = HORIZONTAL\\n')\n f.write('\\tSYMBOL_RATE = {}\\n'.format(\n defs.sym_rate[info['sat']['alias']]))\n f.write('\\tINVERSION = AUTO\\n')\n f.write('\\tMODULATION = QPSK\\n')\n pids = \"+\".join([str(x) for x in defs.pids])\n f.write('\\tVIDEO_PID = {}\\n'.format(pids))\n\n print(\"File \\\"%s\\\" saved.\" % (chan_file))\n\n with open(chan_file, 'r') as f:\n logging.debug(f.read())","function_tokens":["def","_cfg_chan_conf","(","info",",","chan_file",")",":","util",".","print_header","(","\"Channel Configuration\"",")","print","(","textwrap",".","fill","(","\"This step will generate the channel configuration \"","\"file that is required when launching the USB \"","\"receiver in Linux.\"",")","+","\"\\n\"",")","if","(","os",".","path",".","isfile","(","chan_file",")",")",":","print","(","\"Found previous %s file:\"","%","(","chan_file",")",")","if","(","not","util",".","ask_yes_or_no","(","\"Remove and regenerate file?\"",")",")",":","print","(","\"Configuration aborted.\"",")","return","else",":","os",".","remove","(","chan_file",")","with","open","(","chan_file",",","'w'",")","as","f",":","f",".","write","(","'[blocksat-ch]\\n'",")","f",".","write","(","'\\tDELIVERY_SYSTEM = DVBS2\\n'",")","f",".","write","(","'\\tFREQUENCY = %u\\n'","%","(","int","(","info","[","'sat'","]","[","'dl_freq'","]","*","1000",")",")",")","if","(","info","[","'lnb'","]","[","'pol'","]",".","lower","(",")","==","\"dual\"","and","'v1_pointed'","in","info","[","'lnb'","]","and","info","[","'lnb'","]","[","'v1_pointed'","]",")",":","# If a dual-polarization LNB is already pointed for Blocksat v1,","# then we must use the polarization that the LNB was pointed to","# originally, regardless of the satellite signal's polarization. In","# v1, what mattered the most was the power supply voltage, which","# determined the polarization of the dual polarization LNBs. If the","# power supply provides voltage >= 18 (often the case), then the","# LNB necessarily operates currently with horizontal polarization.","# Thus, on channels.conf we must use the same polarization in order","# for the DVB adapter to supply the 18VDC voltage.","if","(","info","[","'lnb'","]","[","\"v1_psu_voltage\"","]",">=","16",")",":","# 16VDC threshold","f",".","write","(","'\\tPOLARIZATION = HORIZONTAL\\n'",")","else",":","f",".","write","(","'\\tPOLARIZATION = VERTICAL\\n'",")","else",":","if","(","info","[","'sat'","]","[","'pol'","]","==","'V'",")",":","f",".","write","(","'\\tPOLARIZATION = VERTICAL\\n'",")","else",":","f",".","write","(","'\\tPOLARIZATION = HORIZONTAL\\n'",")","f",".","write","(","'\\tSYMBOL_RATE = {}\\n'",".","format","(","defs",".","sym_rate","[","info","[","'sat'","]","[","'alias'","]","]",")",")","f",".","write","(","'\\tINVERSION = AUTO\\n'",")","f",".","write","(","'\\tMODULATION = QPSK\\n'",")","pids","=","\"+\"",".","join","(","[","str","(","x",")","for","x","in","defs",".","pids","]",")","f",".","write","(","'\\tVIDEO_PID = {}\\n'",".","format","(","pids",")",")","print","(","\"File \\\"%s\\\" saved.\"","%","(","chan_file",")",")","with","open","(","chan_file",",","'r'",")","as","f",":","logging",".","debug","(","f",".","read","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L445-L498"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_parse_chan_conf","parameters":"(chan_file)","argument_list":"","return_statement":"return chan_conf","docstring":"Convert channel.conf file contents to dictionary","docstring_summary":"Convert channel.conf file contents to dictionary","docstring_tokens":["Convert","channel",".","conf","file","contents","to","dictionary"],"function":"def _parse_chan_conf(chan_file):\n \"\"\"Convert channel.conf file contents to dictionary\"\"\"\n chan_conf = {}\n with open(chan_file, 'r') as f:\n lines = f.read().splitlines()\n for line in lines[1:]:\n key, val = line.split('=')\n chan_conf[key.strip()] = val.strip()\n return chan_conf","function_tokens":["def","_parse_chan_conf","(","chan_file",")",":","chan_conf","=","{","}","with","open","(","chan_file",",","'r'",")","as","f",":","lines","=","f",".","read","(",")",".","splitlines","(",")","for","line","in","lines","[","1",":","]",":","key",",","val","=","line",".","split","(","'='",")","chan_conf","[","key",".","strip","(",")","]","=","val",".","strip","(",")","return","chan_conf"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L501-L509"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_cfg_file_name","parameters":"(cfg_name, directory)","argument_list":"","return_statement":"return os.path.join(directory, json_file)","docstring":"Get the name of the configuration JSON file","docstring_summary":"Get the name of the configuration JSON file","docstring_tokens":["Get","the","name","of","the","configuration","JSON","file"],"function":"def _cfg_file_name(cfg_name, directory):\n \"\"\"Get the name of the configuration JSON file\"\"\"\n # Remove paths\n basename = os.path.basename(cfg_name)\n # Remove extension\n noext = os.path.splitext(basename)[0]\n # Add JSON extension\n json_file = noext + \".json\"\n return os.path.join(directory, json_file)","function_tokens":["def","_cfg_file_name","(","cfg_name",",","directory",")",":","# Remove paths","basename","=","os",".","path",".","basename","(","cfg_name",")","# Remove extension","noext","=","os",".","path",".","splitext","(","basename",")","[","0","]","# Add JSON extension","json_file","=","noext","+","\".json\"","return","os",".","path",".","join","(","directory",",","json_file",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L512-L520"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_read_cfg_file","parameters":"(cfg_file)","argument_list":"","return_statement":"","docstring":"Read configuration file","docstring_summary":"Read configuration file","docstring_tokens":["Read","configuration","file"],"function":"def _read_cfg_file(cfg_file):\n \"\"\"Read configuration file\"\"\"\n\n if (os.path.isfile(cfg_file)):\n with open(cfg_file) as fd:\n info = json.load(fd)\n return info","function_tokens":["def","_read_cfg_file","(","cfg_file",")",":","if","(","os",".","path",".","isfile","(","cfg_file",")",")",":","with","open","(","cfg_file",")","as","fd",":","info","=","json",".","load","(","fd",")","return","info"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L523-L529"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_write_cfg_file","parameters":"(cfg_file, user_info)","argument_list":"","return_statement":"","docstring":"Write configuration file","docstring_summary":"Write configuration file","docstring_tokens":["Write","configuration","file"],"function":"def _write_cfg_file(cfg_file, user_info):\n \"\"\"Write configuration file\"\"\"\n with open(cfg_file, 'w') as fd:\n json.dump(user_info, fd)","function_tokens":["def","_write_cfg_file","(","cfg_file",",","user_info",")",":","with","open","(","cfg_file",",","'w'",")","as","fd",":","json",".","dump","(","user_info",",","fd",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L532-L535"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"_rst_cfg_file","parameters":"(cfg_file)","argument_list":"","return_statement":"return True","docstring":"Reset a previous configuration file in case it exists","docstring_summary":"Reset a previous configuration file in case it exists","docstring_tokens":["Reset","a","previous","configuration","file","in","case","it","exists"],"function":"def _rst_cfg_file(cfg_file):\n \"\"\"Reset a previous configuration file in case it exists\"\"\"\n info = _read_cfg_file(cfg_file)\n\n if (info is not None):\n print(\"Found previous configuration:\")\n pprint(info, width=80, compact=False)\n if (util.ask_yes_or_no(\"Reset?\")):\n os.remove(cfg_file)\n else:\n print(\"Configuration aborted.\")\n return False\n return True","function_tokens":["def","_rst_cfg_file","(","cfg_file",")",":","info","=","_read_cfg_file","(","cfg_file",")","if","(","info","is","not","None",")",":","print","(","\"Found previous configuration:\"",")","pprint","(","info",",","width","=","80",",","compact","=","False",")","if","(","util",".","ask_yes_or_no","(","\"Reset?\"",")",")",":","os",".","remove","(","cfg_file",")","else",":","print","(","\"Configuration aborted.\"",")","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L538-L550"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"read_cfg_file","parameters":"(cfg_name, directory)","argument_list":"","return_statement":"return info","docstring":"Read configuration file\n\n If not available, run configuration helper.","docstring_summary":"Read configuration file","docstring_tokens":["Read","configuration","file"],"function":"def read_cfg_file(cfg_name, directory):\n \"\"\"Read configuration file\n\n If not available, run configuration helper.\n\n \"\"\"\n cfg_file = _cfg_file_name(cfg_name, directory)\n info = _read_cfg_file(cfg_file)\n\n while (info is None):\n print(\"Missing {} configuration file\".format(cfg_file))\n if (util.ask_yes_or_no(\"Run configuration helper now?\")):\n configure(Namespace(cfg_dir=directory, cfg=cfg_name))\n else:\n print(\"Abort\")\n return\n\n info = _read_cfg_file(cfg_file)\n\n return info","function_tokens":["def","read_cfg_file","(","cfg_name",",","directory",")",":","cfg_file","=","_cfg_file_name","(","cfg_name",",","directory",")","info","=","_read_cfg_file","(","cfg_file",")","while","(","info","is","None",")",":","print","(","\"Missing {} configuration file\"",".","format","(","cfg_file",")",")","if","(","util",".","ask_yes_or_no","(","\"Run configuration helper now?\"",")",")",":","configure","(","Namespace","(","cfg_dir","=","directory",",","cfg","=","cfg_name",")",")","else",":","print","(","\"Abort\"",")","return","info","=","_read_cfg_file","(","cfg_file",")","return","info"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L553-L572"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"write_cfg_file","parameters":"(cfg_name, directory, user_info)","argument_list":"","return_statement":"","docstring":"Write configuration file","docstring_summary":"Write configuration file","docstring_tokens":["Write","configuration","file"],"function":"def write_cfg_file(cfg_name, directory, user_info):\n \"\"\"Write configuration file\"\"\"\n cfg_file = _cfg_file_name(cfg_name, directory)\n _write_cfg_file(cfg_file, user_info)","function_tokens":["def","write_cfg_file","(","cfg_name",",","directory",",","user_info",")",":","cfg_file","=","_cfg_file_name","(","cfg_name",",","directory",")","_write_cfg_file","(","cfg_file",",","user_info",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L575-L578"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"get_rx_model","parameters":"(user_info)","argument_list":"","return_statement":"return (user_info['setup']['vendor'] + \" \" +\n user_info['setup']['model']).strip()","docstring":"Return string with the receiver vendor and model\n\n Note: this function differs from _get_rx_marketing_name(). The latter\n includes the satellite kit name. In contrast, this function returns the raw\n vendeor-model string.","docstring_summary":"Return string with the receiver vendor and model","docstring_tokens":["Return","string","with","the","receiver","vendor","and","model"],"function":"def get_rx_model(user_info):\n \"\"\"Return string with the receiver vendor and model\n\n Note: this function differs from _get_rx_marketing_name(). The latter\n includes the satellite kit name. In contrast, this function returns the raw\n vendeor-model string.\n\n \"\"\"\n return (user_info['setup']['vendor'] + \" \" +\n user_info['setup']['model']).strip()","function_tokens":["def","get_rx_model","(","user_info",")",":","return","(","user_info","[","'setup'","]","[","'vendor'","]","+","\" \"","+","user_info","[","'setup'","]","[","'model'","]",")",".","strip","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L581-L590"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"get_antenna_model","parameters":"(user_info)","argument_list":"","return_statement":"return antenna","docstring":"Return string with the antenna model","docstring_summary":"Return string with the antenna model","docstring_tokens":["Return","string","with","the","antenna","model"],"function":"def get_antenna_model(user_info):\n \"\"\"Return string with the antenna model\"\"\"\n antenna_info = user_info['setup']['antenna']\n antenna_type = antenna_info.get('type')\n\n if (antenna_type == 'dish' or antenna_info['label'] == 'custom'):\n dish_size = antenna_info['size']\n if (dish_size >= 100):\n antenna = \"{:g}m dish\".format(dish_size \/ 100)\n else:\n antenna = \"{:g}cm dish\".format(dish_size)\n else:\n return antenna_info['label']\n\n return antenna","function_tokens":["def","get_antenna_model","(","user_info",")",":","antenna_info","=","user_info","[","'setup'","]","[","'antenna'","]","antenna_type","=","antenna_info",".","get","(","'type'",")","if","(","antenna_type","==","'dish'","or","antenna_info","[","'label'","]","==","'custom'",")",":","dish_size","=","antenna_info","[","'size'","]","if","(","dish_size",">=","100",")",":","antenna","=","\"{:g}m dish\"",".","format","(","dish_size","\/","100",")","else",":","antenna","=","\"{:g}cm dish\"",".","format","(","dish_size",")","else",":","return","antenna_info","[","'label'","]","return","antenna"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L593-L607"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"get_lnb_model","parameters":"(user_info)","argument_list":"","return_statement":"return lnb","docstring":"Return string with the LNB model","docstring_summary":"Return string with the LNB model","docstring_tokens":["Return","string","with","the","LNB","model"],"function":"def get_lnb_model(user_info):\n \"\"\"Return string with the LNB model\"\"\"\n lnb_info = user_info['lnb']\n if (lnb_info['vendor'] == \"\" and lnb_info['model'] == \"\"):\n if (lnb_info['universal']):\n lnb = \"Custom Universal LNB\"\n else:\n lnb = \"Custom {}-band LNB\".format(lnb_info['band'])\n else:\n lnb = \"{} {}\".format(lnb_info['vendor'], lnb_info['model'])\n return lnb","function_tokens":["def","get_lnb_model","(","user_info",")",":","lnb_info","=","user_info","[","'lnb'","]","if","(","lnb_info","[","'vendor'","]","==","\"\"","and","lnb_info","[","'model'","]","==","\"\"",")",":","if","(","lnb_info","[","'universal'","]",")",":","lnb","=","\"Custom Universal LNB\"","else",":","lnb","=","\"Custom {}-band LNB\"",".","format","(","lnb_info","[","'band'","]",")","else",":","lnb","=","\"{} {}\"",".","format","(","lnb_info","[","'vendor'","]",",","lnb_info","[","'model'","]",")","return","lnb"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L610-L620"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"get_net_if","parameters":"(user_info)","argument_list":"","return_statement":"return interface","docstring":"Get the network interface used by the given setup","docstring_summary":"Get the network interface used by the given setup","docstring_tokens":["Get","the","network","interface","used","by","the","given","setup"],"function":"def get_net_if(user_info):\n \"\"\"Get the network interface used by the given setup\"\"\"\n if (user_info is None):\n raise ValueError(\"Failed to read local configuration\")\n\n setup_type = user_info['setup']['type']\n\n if (setup_type in [defs.sdr_setup_type, defs.sat_ip_setup_type]):\n interface = \"lo\"\n elif (setup_type == defs.linux_usb_setup_type):\n if ('adapter' not in user_info['setup']):\n interface = \"dvb0_0\"\n logger.warning(\"Could not find the dvbnet interface name. \"\n \"Is the {} receiver running?\".format(\n get_rx_model(user_info)))\n logger.warning(\"Assuming interface name {}.\".format(interface))\n else:\n adapter = user_info['setup']['adapter']\n interface = \"dvb{}_0\".format(adapter)\n elif (setup_type == defs.standalone_setup_type):\n interface = user_info['setup']['netdev']\n else:\n raise ValueError(\"Unknown setup type\")\n return interface","function_tokens":["def","get_net_if","(","user_info",")",":","if","(","user_info","is","None",")",":","raise","ValueError","(","\"Failed to read local configuration\"",")","setup_type","=","user_info","[","'setup'","]","[","'type'","]","if","(","setup_type","in","[","defs",".","sdr_setup_type",",","defs",".","sat_ip_setup_type","]",")",":","interface","=","\"lo\"","elif","(","setup_type","==","defs",".","linux_usb_setup_type",")",":","if","(","'adapter'","not","in","user_info","[","'setup'","]",")",":","interface","=","\"dvb0_0\"","logger",".","warning","(","\"Could not find the dvbnet interface name. \"","\"Is the {} receiver running?\"",".","format","(","get_rx_model","(","user_info",")",")",")","logger",".","warning","(","\"Assuming interface name {}.\"",".","format","(","interface",")",")","else",":","adapter","=","user_info","[","'setup'","]","[","'adapter'","]","interface","=","\"dvb{}_0\"",".","format","(","adapter",")","elif","(","setup_type","==","defs",".","standalone_setup_type",")",":","interface","=","user_info","[","'setup'","]","[","'netdev'","]","else",":","raise","ValueError","(","\"Unknown setup type\"",")","return","interface"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L623-L646"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Argument parser of config command","docstring_summary":"Argument parser of config command","docstring_tokens":["Argument","parser","of","config","command"],"function":"def subparser(subparsers):\n \"\"\"Argument parser of config command\"\"\"\n p = subparsers.add_parser('config',\n aliases=['cfg'],\n description=\"Configure Blocksat Rx setup\",\n help='Define receiver and Bitcoin Satellite \\\n configurations',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.set_defaults(func=configure)\n\n subsubparsers = p.add_subparsers(title='subcommands',\n help='Target sub-command')\n p2 = subsubparsers.add_parser(\n 'show',\n description=\"Display the local configuration\",\n help='Display the local configuration',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p2.set_defaults(func=show)\n\n p3 = subsubparsers.add_parser(\n 'channel',\n description=\"Configure the channels file used by the USB receiver\",\n help='Configure the channels file used by the USB receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p3.set_defaults(func=channel)\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'config'",",","aliases","=","[","'cfg'","]",",","description","=","\"Configure Blocksat Rx setup\"",",","help","=","'Define receiver and Bitcoin Satellite \\\n configurations'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","set_defaults","(","func","=","configure",")","subsubparsers","=","p",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",")","p2","=","subsubparsers",".","add_parser","(","'show'",",","description","=","\"Display the local configuration\"",",","help","=","'Display the local configuration'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p2",".","set_defaults","(","func","=","show",")","p3","=","subsubparsers",".","add_parser","(","'channel'",",","description","=","\"Configure the channels file used by the USB receiver\"",",","help","=","'Configure the channels file used by the USB receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p3",".","set_defaults","(","func","=","channel",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L649-L674"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"configure","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Configure Blocksat Receiver setup","docstring_summary":"Configure Blocksat Receiver setup","docstring_tokens":["Configure","Blocksat","Receiver","setup"],"function":"def configure(args):\n \"\"\"Configure Blocksat Receiver setup\n\n \"\"\"\n cfg_file = _cfg_file_name(args.cfg, args.cfg_dir)\n rst_ok = _rst_cfg_file(cfg_file)\n if (not rst_ok):\n return\n\n try:\n user_sat = _cfg_satellite()\n user_setup = _cfg_rx_setup()\n user_lnb = _cfg_lnb(user_sat, user_setup)\n user_freqs = _cfg_frequencies(user_sat, user_lnb, user_setup)\n except KeyboardInterrupt:\n print(\"\\nAbort\")\n sys.exit(1)\n\n user_info = {\n 'sat': user_sat,\n 'setup': user_setup,\n 'lnb': user_lnb,\n 'freqs': user_freqs\n }\n\n logging.debug(pformat(user_info))\n\n if not os.path.exists(args.cfg_dir):\n os.makedirs(args.cfg_dir)\n\n # Channel configuration file\n if (user_setup['type'] == defs.linux_usb_setup_type):\n chan_file = os.path.join(args.cfg_dir, args.cfg + \"-channel.conf\")\n _cfg_chan_conf(user_info, chan_file)\n user_info['setup']['channel'] = chan_file\n\n # Create the JSON configuration file\n _write_cfg_file(cfg_file, user_info)\n\n os.system('clear')\n util.print_header(\"JSON configuration file\")\n print(\"Saved configurations on %s\" % (cfg_file))\n\n util.print_header(\"Next Steps\")\n\n print(textwrap.fill(\"Please check setup instructions by running:\"))\n print(\"\"\"\n blocksat-cli instructions\n \"\"\")","function_tokens":["def","configure","(","args",")",":","cfg_file","=","_cfg_file_name","(","args",".","cfg",",","args",".","cfg_dir",")","rst_ok","=","_rst_cfg_file","(","cfg_file",")","if","(","not","rst_ok",")",":","return","try",":","user_sat","=","_cfg_satellite","(",")","user_setup","=","_cfg_rx_setup","(",")","user_lnb","=","_cfg_lnb","(","user_sat",",","user_setup",")","user_freqs","=","_cfg_frequencies","(","user_sat",",","user_lnb",",","user_setup",")","except","KeyboardInterrupt",":","print","(","\"\\nAbort\"",")","sys",".","exit","(","1",")","user_info","=","{","'sat'",":","user_sat",",","'setup'",":","user_setup",",","'lnb'",":","user_lnb",",","'freqs'",":","user_freqs","}","logging",".","debug","(","pformat","(","user_info",")",")","if","not","os",".","path",".","exists","(","args",".","cfg_dir",")",":","os",".","makedirs","(","args",".","cfg_dir",")","# Channel configuration file","if","(","user_setup","[","'type'","]","==","defs",".","linux_usb_setup_type",")",":","chan_file","=","os",".","path",".","join","(","args",".","cfg_dir",",","args",".","cfg","+","\"-channel.conf\"",")","_cfg_chan_conf","(","user_info",",","chan_file",")","user_info","[","'setup'","]","[","'channel'","]","=","chan_file","# Create the JSON configuration file","_write_cfg_file","(","cfg_file",",","user_info",")","os",".","system","(","'clear'",")","util",".","print_header","(","\"JSON configuration file\"",")","print","(","\"Saved configurations on %s\"","%","(","cfg_file",")",")","util",".","print_header","(","\"Next Steps\"",")","print","(","textwrap",".","fill","(","\"Please check setup instructions by running:\"",")",")","print","(","\"\"\"\n blocksat-cli instructions\n \"\"\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L677-L725"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"show","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Print the local configuration","docstring_summary":"Print the local configuration","docstring_tokens":["Print","the","local","configuration"],"function":"def show(args):\n \"\"\"Print the local configuration\"\"\"\n info = read_cfg_file(args.cfg, args.cfg_dir)\n if (info is None):\n return\n print(\"| {:30s} | {:25s} |\".format(\"Receiver\",\n _get_rx_marketing_name(info['setup'])))\n print(\"| {:30s} | {:25s} |\".format(\"LNB\", get_lnb_model(info)))\n print(\"| {:30s} | {:25s} |\".format(\"Antenna\", get_antenna_model(info)))\n pr_cfgs = {\n 'freqs': {\n 'dl': (\"Downlink frequency\", \"MHz\", None),\n 'lo': (\"LNB LO frequency\", \"MHz\", None),\n 'l_band': (\"Receiver L-band frequency\", \"MHz\", None)\n },\n 'sat': {\n 'name': (\"Satellite name\", \"\", None),\n 'band': (\"Signal band\", \"\", None),\n 'pol': (\"Signal polarization\", \"\", lambda x: \"Horizontal\"\n if x == \"H\" else \"vertical\"),\n }\n }\n for category in pr_cfgs:\n for key, pr_cfg in pr_cfgs[category].items():\n label = pr_cfg[0]\n unit = pr_cfg[1]\n val = info[category][key]\n # Transform the value if a callback is defined\n if (pr_cfg[2] is not None):\n val = pr_cfg[2](val)\n print(\"| {:30s} | {:25s} |\".format(label, str(val) + \" \" + unit))","function_tokens":["def","show","(","args",")",":","info","=","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","info","is","None",")",":","return","print","(","\"| {:30s} | {:25s} |\"",".","format","(","\"Receiver\"",",","_get_rx_marketing_name","(","info","[","'setup'","]",")",")",")","print","(","\"| {:30s} | {:25s} |\"",".","format","(","\"LNB\"",",","get_lnb_model","(","info",")",")",")","print","(","\"| {:30s} | {:25s} |\"",".","format","(","\"Antenna\"",",","get_antenna_model","(","info",")",")",")","pr_cfgs","=","{","'freqs'",":","{","'dl'",":","(","\"Downlink frequency\"",",","\"MHz\"",",","None",")",",","'lo'",":","(","\"LNB LO frequency\"",",","\"MHz\"",",","None",")",",","'l_band'",":","(","\"Receiver L-band frequency\"",",","\"MHz\"",",","None",")","}",",","'sat'",":","{","'name'",":","(","\"Satellite name\"",",","\"\"",",","None",")",",","'band'",":","(","\"Signal band\"",",","\"\"",",","None",")",",","'pol'",":","(","\"Signal polarization\"",",","\"\"",",","lambda","x",":","\"Horizontal\"","if","x","==","\"H\"","else","\"vertical\"",")",",","}","}","for","category","in","pr_cfgs",":","for","key",",","pr_cfg","in","pr_cfgs","[","category","]",".","items","(",")",":","label","=","pr_cfg","[","0","]","unit","=","pr_cfg","[","1","]","val","=","info","[","category","]","[","key","]","# Transform the value if a callback is defined","if","(","pr_cfg","[","2","]","is","not","None",")",":","val","=","pr_cfg","[","2","]","(","val",")","print","(","\"| {:30s} | {:25s} |\"",".","format","(","label",",","str","(","val",")","+","\" \"","+","unit",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L728-L758"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/config.py","language":"python","identifier":"channel","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Configure the channels.conf file directly","docstring_summary":"Configure the channels.conf file directly","docstring_tokens":["Configure","the","channels",".","conf","file","directly"],"function":"def channel(args):\n \"\"\"Configure the channels.conf file directly\"\"\"\n user_info = read_cfg_file(args.cfg, args.cfg_dir)\n if (user_info is None):\n return\n\n # Channel configuration file\n if (user_info['setup']['type'] != defs.linux_usb_setup_type):\n raise TypeError(\"Invalid command for {} receivers\".format(\n user_info['setup']['type']))\n\n chan_file = os.path.join(args.cfg_dir, args.cfg + \"-channel.conf\")\n _cfg_chan_conf(user_info, chan_file)\n\n # Overwrite the channels.conf path in case it is changing from a previous\n # version of the CLI when the conf file name was not bound to the cfg name\n user_info['setup']['channel'] = chan_file\n write_cfg_file(args.cfg, args.cfg_dir, user_info)","function_tokens":["def","channel","(","args",")",":","user_info","=","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","user_info","is","None",")",":","return","# Channel configuration file","if","(","user_info","[","'setup'","]","[","'type'","]","!=","defs",".","linux_usb_setup_type",")",":","raise","TypeError","(","\"Invalid command for {} receivers\"",".","format","(","user_info","[","'setup'","]","[","'type'","]",")",")","chan_file","=","os",".","path",".","join","(","args",".","cfg_dir",",","args",".","cfg","+","\"-channel.conf\"",")","_cfg_chan_conf","(","user_info",",","chan_file",")","# Overwrite the channels.conf path in case it is changing from a previous","# version of the CLI when the conf file name was not bound to the cfg name","user_info","[","'setup'","]","[","'channel'","]","=","chan_file","write_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",",","user_info",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/config.py#L761-L778"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"_print_s400_instructions","parameters":"(info)","argument_list":"","return_statement":"","docstring":"Print instructions for configuration of the Novra S400","docstring_summary":"Print instructions for configuration of the Novra S400","docstring_tokens":["Print","instructions","for","configuration","of","the","Novra","S400"],"function":"def _print_s400_instructions(info):\n \"\"\"Print instructions for configuration of the Novra S400\n \"\"\"\n util.print_header(\"Novra S400\")\n\n _print(\"\"\"\n The Novra S400 is a standalone receiver, which will receive data from\n satellite and output IP packets to the host over the network. Hence, you\n will need to configure both the S400 and the host.\n \"\"\")\n\n util.print_sub_header(\"Connections\")\n\n _print(\"The Novra S400 can be connected as follows:\")\n\n print((\"LNB ----> S400 (RF1 Interface) -- \"\n \"S400 (LAN 1 Interface) ----> Host \/ Network\\n\"))\n\n _item(\"Connect the LNB directly to interface RF1 of the S400 using a \"\n \"coaxial cable (an RG6 cable is recommended).\")\n _item(\"Connect the S400's LAN1 interface to your computer or network.\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Network Connection\")\n\n _print(\"Next, make sure the S400 receiver is reachable by the host.\")\n\n _print(\"First, configure your host's network interface to the same subnet \"\n \"as the S400. By default, the S400 is configured with IP address \"\n \"192.168.1.2 on LAN1 and 192.168.2.2 on LAN2. Hence, if you \"\n \"connect to LAN1, make sure your host's network interface has IP \"\n \"address 192.168.1.x, where \\\"x\\\" could be any number higher than \"\n \"2. For example, you could configure your host's network interface \"\n \"with IP address 192.168.1.3.\")\n\n _print(\"After that, open the browser and access 192.168.1.2 (or \"\n \"192.168.2.2 if connected to LAN 2). The web management console \"\n \"should open up successfully.\")\n\n print()\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Software Requirements\")\n\n _print(\"Next, install all software pre-requisites on your host. Run:\")\n\n print(\" blocksat-cli deps install\\n\")\n\n _print(\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers.\"\"\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Receiver and Host Configuration\")\n\n print(\"Now, configure the S400 receiver and the host by running:\")\n\n print(\"\\n blocksat-cli standalone cfg\\n\")\n\n _print(\"\"\"If you would like to review the changes that will be made to the\n host before applying them, first run the command in dry-run mode:\"\"\")\n\n print(\" blocksat-cli standalone cfg --dry-run\\n\\n\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Monitoring\")\n\n print(\"Finally, you can monitor your receiver by running:\")\n\n print(\"\\n blocksat-cli standalone monitor\\n\\n\")\n\n util.prompt_for_enter()","function_tokens":["def","_print_s400_instructions","(","info",")",":","util",".","print_header","(","\"Novra S400\"",")","_print","(","\"\"\"\n The Novra S400 is a standalone receiver, which will receive data from\n satellite and output IP packets to the host over the network. Hence, you\n will need to configure both the S400 and the host.\n \"\"\"",")","util",".","print_sub_header","(","\"Connections\"",")","_print","(","\"The Novra S400 can be connected as follows:\"",")","print","(","(","\"LNB ----> S400 (RF1 Interface) -- \"","\"S400 (LAN 1 Interface) ----> Host \/ Network\\n\"",")",")","_item","(","\"Connect the LNB directly to interface RF1 of the S400 using a \"","\"coaxial cable (an RG6 cable is recommended).\"",")","_item","(","\"Connect the S400's LAN1 interface to your computer or network.\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Network Connection\"",")","_print","(","\"Next, make sure the S400 receiver is reachable by the host.\"",")","_print","(","\"First, configure your host's network interface to the same subnet \"","\"as the S400. By default, the S400 is configured with IP address \"","\"192.168.1.2 on LAN1 and 192.168.2.2 on LAN2. Hence, if you \"","\"connect to LAN1, make sure your host's network interface has IP \"","\"address 192.168.1.x, where \\\"x\\\" could be any number higher than \"","\"2. For example, you could configure your host's network interface \"","\"with IP address 192.168.1.3.\"",")","_print","(","\"After that, open the browser and access 192.168.1.2 (or \"","\"192.168.2.2 if connected to LAN 2). The web management console \"","\"should open up successfully.\"",")","print","(",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Software Requirements\"",")","_print","(","\"Next, install all software pre-requisites on your host. Run:\"",")","print","(","\" blocksat-cli deps install\\n\"",")","_print","(","\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers.\"\"\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Receiver and Host Configuration\"",")","print","(","\"Now, configure the S400 receiver and the host by running:\"",")","print","(","\"\\n blocksat-cli standalone cfg\\n\"",")","_print","(","\"\"\"If you would like to review the changes that will be made to the\n host before applying them, first run the command in dry-run mode:\"\"\"",")","print","(","\" blocksat-cli standalone cfg --dry-run\\n\\n\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Monitoring\"",")","print","(","\"Finally, you can monitor your receiver by running:\"",")","print","(","\"\\n blocksat-cli standalone monitor\\n\\n\"",")","util",".","prompt_for_enter","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L20-L94"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"_print_usb_rx_instructions","parameters":"(info)","argument_list":"","return_statement":"","docstring":"Print instructions for runnning with a Linux USB receiver","docstring_summary":"Print instructions for runnning with a Linux USB receiver","docstring_tokens":["Print","instructions","for","runnning","with","a","Linux","USB","receiver"],"function":"def _print_usb_rx_instructions(info):\n \"\"\"Print instructions for runnning with a Linux USB receiver\n \"\"\"\n\n name = (info['setup']['vendor'] + \" \" + info['setup']['model']).strip()\n\n util.print_header(name)\n\n _print(\"\"\"\n The {0} is a USB receiver, which will receive data from satellite and will\n output data to the host over USB. The host, in turn, is responsible for\n configuring the receiver using specific DVB-S2 tools. Hence, next, you need\n to prepare the host for driving the {0}.\n \"\"\".format(name))\n\n util.print_sub_header(\"Hardware Connections\")\n\n print(\"The {} should be connected as follows:\\n\".format(name))\n\n print((\"LNB ----> {0} (LNB Interface) -- \"\n \"{0} (USB Interface) ----> Host\\n\".format(name)))\n\n _item(\"Connect the LNB directly to \\\"LNB IN\\\" of the {} using a coaxial\"\n \" cable (an RG6 cable is recommended).\".format(name))\n _item(\"Connect the {}'s USB interface to your computer.\".format(name))\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Drivers\")\n\n _print(\"\"\"\n Before anything else, note that specific device drivers are required in\n order to use the {0}. Please, do note that driver installation can cause\n corruptions and, therefore, it is safer and **strongly recommended** to use\n a virtual machine for running the {0}. If you do so, please note that all\n commands recommended in the remainder of this page are supposed to be\n executed in the virtual machine.\n \"\"\".format(name))\n\n _print(\"Next, install the drivers for the {0} by running:\".format(name))\n\n print(\"\"\"\n blocksat-cli deps tbs-drivers\n \"\"\")\n\n print(\"Once the script completes the installation, reboot the virtual \"\n \"machine.\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Host Requirements\")\n\n print(\n \"Now, install all pre-requisites (in the virtual machine) by running:\")\n\n print(\"\"\"\n blocksat-cli deps install\n \"\"\")\n\n _print(\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers. For\n other package managers, refer to the instructions at:\"\"\")\n print(defs.user_guide_url + \"doc\/tbs.html\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Configure the Host\")\n\n _print(\n \"\"\"Next, you need to create and configure the network interfaces that\n will output the IP traffic received via the TBS5927. You can apply all\n configurations by running the following command:\"\"\")\n\n print(\"\\n blocksat-cli usb config\\n\")\n\n _print(\"\"\"If you would like to review the changes that will be made before\n applying them, first run the command in dry-run mode:\n \"\"\")\n\n print(\"\\n blocksat-cli usb config --dry-run\\n\")\n\n _print(\"\"\"\n Note this command will define arbitrary IP addresses to the interfaces. If\n you need (or want) to define specific IP addresses instead, for example to\n avoid IP address conflicts, use command-line argument `--ip`.\n \"\"\")\n\n _print(\n \"\"\"Furthermore, note that this configuration is not persistent across\n reboots. After a reboot, you need to run `blocksat-cli usb config`\n again.\"\"\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Launch\")\n\n print(\"Finally, start the receiver by running:\")\n\n print(\"\\n blocksat-cli usb launch\\n\")\n\n util.prompt_for_enter()","function_tokens":["def","_print_usb_rx_instructions","(","info",")",":","name","=","(","info","[","'setup'","]","[","'vendor'","]","+","\" \"","+","info","[","'setup'","]","[","'model'","]",")",".","strip","(",")","util",".","print_header","(","name",")","_print","(","\"\"\"\n The {0} is a USB receiver, which will receive data from satellite and will\n output data to the host over USB. The host, in turn, is responsible for\n configuring the receiver using specific DVB-S2 tools. Hence, next, you need\n to prepare the host for driving the {0}.\n \"\"\"",".","format","(","name",")",")","util",".","print_sub_header","(","\"Hardware Connections\"",")","print","(","\"The {} should be connected as follows:\\n\"",".","format","(","name",")",")","print","(","(","\"LNB ----> {0} (LNB Interface) -- \"","\"{0} (USB Interface) ----> Host\\n\"",".","format","(","name",")",")",")","_item","(","\"Connect the LNB directly to \\\"LNB IN\\\" of the {} using a coaxial\"","\" cable (an RG6 cable is recommended).\"",".","format","(","name",")",")","_item","(","\"Connect the {}'s USB interface to your computer.\"",".","format","(","name",")",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Drivers\"",")","_print","(","\"\"\"\n Before anything else, note that specific device drivers are required in\n order to use the {0}. Please, do note that driver installation can cause\n corruptions and, therefore, it is safer and **strongly recommended** to use\n a virtual machine for running the {0}. If you do so, please note that all\n commands recommended in the remainder of this page are supposed to be\n executed in the virtual machine.\n \"\"\"",".","format","(","name",")",")","_print","(","\"Next, install the drivers for the {0} by running:\"",".","format","(","name",")",")","print","(","\"\"\"\n blocksat-cli deps tbs-drivers\n \"\"\"",")","print","(","\"Once the script completes the installation, reboot the virtual \"","\"machine.\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Host Requirements\"",")","print","(","\"Now, install all pre-requisites (in the virtual machine) by running:\"",")","print","(","\"\"\"\n blocksat-cli deps install\n \"\"\"",")","_print","(","\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers. For\n other package managers, refer to the instructions at:\"\"\"",")","print","(","defs",".","user_guide_url","+","\"doc\/tbs.html\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Configure the Host\"",")","_print","(","\"\"\"Next, you need to create and configure the network interfaces that\n will output the IP traffic received via the TBS5927. You can apply all\n configurations by running the following command:\"\"\"",")","print","(","\"\\n blocksat-cli usb config\\n\"",")","_print","(","\"\"\"If you would like to review the changes that will be made before\n applying them, first run the command in dry-run mode:\n \"\"\"",")","print","(","\"\\n blocksat-cli usb config --dry-run\\n\"",")","_print","(","\"\"\"\n Note this command will define arbitrary IP addresses to the interfaces. If\n you need (or want) to define specific IP addresses instead, for example to\n avoid IP address conflicts, use command-line argument `--ip`.\n \"\"\"",")","_print","(","\"\"\"Furthermore, note that this configuration is not persistent across\n reboots. After a reboot, you need to run `blocksat-cli usb config`\n again.\"\"\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Launch\"",")","print","(","\"Finally, start the receiver by running:\"",")","print","(","\"\\n blocksat-cli usb launch\\n\"",")","util",".","prompt_for_enter","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L97-L197"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"_print_sdr_instructions","parameters":"(info)","argument_list":"","return_statement":"","docstring":"Print instruction for configuration of an SDR setup","docstring_summary":"Print instruction for configuration of an SDR setup","docstring_tokens":["Print","instruction","for","configuration","of","an","SDR","setup"],"function":"def _print_sdr_instructions(info):\n \"\"\"Print instruction for configuration of an SDR setup\n \"\"\"\n util.print_header(\"SDR Setup\")\n\n util.print_sub_header(\"Connections\")\n\n print(\"The SDR setup is connected as follows:\\n\")\n\n print(\"LNB ----> Power Supply ----> RTL-SDR ----> Host\\n\")\n\n _item(\"Connect the RTL-SDR USB dongle to your host PC.\")\n _item(\"Connect the **non-powered** port of the power supply (labeled as \"\n \"\\\"Signal to IRD\\\") to the RTL-SDR using an SMA cable and an \"\n \"SMA-to-F adapter.\")\n _item(\"Connect the **powered** port (labeled \\\"Signal to SWM\\\") of the \"\n \"power supply to the LNB using a coaxial cable (an RG6 cable is \"\n \"recommended).\")\n\n print()\n _print(\"IMPORTANT: Do NOT connect the powered port of the power supply \"\n \"to the SDR interface. Permanent damage may occur to your SDR \"\n \"and\/or your computer.\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Software Requirements\")\n\n print(\"The SDR-based setup relies on the applications listed below:\\n\")\n\n _item(\"leandvb: a software-based DVB-S2 receiver application.\")\n _item(\"rtl_sdr: reads samples taken by the RTL-SDR and feeds them into \"\n \"leandvb.\")\n _item(\"TSDuck: unpacks the output of leandvb and produces \"\n \"IP packets to be fed to Bitcoin Satellite.\")\n _item(\"Gqrx: useful for spectrum visualization during antenna pointing.\")\n\n print(\"\\nTo install them, run:\")\n print(\"\"\"\n blocksat-cli deps install\n \"\"\")\n\n _print(\"\"\"\n NOTE: This command supports the two most recent Ubuntu LTS, Fedora, and\n CentOS releases. In case you are using another Linux distribution or\n version, please refer to the manual compilation and installation\n instructions at:\"\"\")\n print(defs.user_guide_url + \"doc\/sdr.html\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Configuration\")\n\n _print(\n \"Next, you can generate the configurations that are needed for gqrx \"\n \"by running:\")\n\n print(\" blocksat-cli gqrx-conf\")\n\n util.prompt_for_enter()\n\n util.print_sub_header(\"Running\")\n\n _print(\n \"You should now be ready to launch the SDR receiver. You can run it \"\n \"by executing:\")\n\n print(\" blocksat-cli sdr\\n\")\n print(\"Or, in GUI mode:\\n\")\n print(\" blocksat-cli sdr --gui\\n\")\n\n util.prompt_for_enter()","function_tokens":["def","_print_sdr_instructions","(","info",")",":","util",".","print_header","(","\"SDR Setup\"",")","util",".","print_sub_header","(","\"Connections\"",")","print","(","\"The SDR setup is connected as follows:\\n\"",")","print","(","\"LNB ----> Power Supply ----> RTL-SDR ----> Host\\n\"",")","_item","(","\"Connect the RTL-SDR USB dongle to your host PC.\"",")","_item","(","\"Connect the **non-powered** port of the power supply (labeled as \"","\"\\\"Signal to IRD\\\") to the RTL-SDR using an SMA cable and an \"","\"SMA-to-F adapter.\"",")","_item","(","\"Connect the **powered** port (labeled \\\"Signal to SWM\\\") of the \"","\"power supply to the LNB using a coaxial cable (an RG6 cable is \"","\"recommended).\"",")","print","(",")","_print","(","\"IMPORTANT: Do NOT connect the powered port of the power supply \"","\"to the SDR interface. Permanent damage may occur to your SDR \"","\"and\/or your computer.\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Software Requirements\"",")","print","(","\"The SDR-based setup relies on the applications listed below:\\n\"",")","_item","(","\"leandvb: a software-based DVB-S2 receiver application.\"",")","_item","(","\"rtl_sdr: reads samples taken by the RTL-SDR and feeds them into \"","\"leandvb.\"",")","_item","(","\"TSDuck: unpacks the output of leandvb and produces \"","\"IP packets to be fed to Bitcoin Satellite.\"",")","_item","(","\"Gqrx: useful for spectrum visualization during antenna pointing.\"",")","print","(","\"\\nTo install them, run:\"",")","print","(","\"\"\"\n blocksat-cli deps install\n \"\"\"",")","_print","(","\"\"\"\n NOTE: This command supports the two most recent Ubuntu LTS, Fedora, and\n CentOS releases. In case you are using another Linux distribution or\n version, please refer to the manual compilation and installation\n instructions at:\"\"\"",")","print","(","defs",".","user_guide_url","+","\"doc\/sdr.html\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Configuration\"",")","_print","(","\"Next, you can generate the configurations that are needed for gqrx \"","\"by running:\"",")","print","(","\" blocksat-cli gqrx-conf\"",")","util",".","prompt_for_enter","(",")","util",".","print_sub_header","(","\"Running\"",")","_print","(","\"You should now be ready to launch the SDR receiver. You can run it \"","\"by executing:\"",")","print","(","\" blocksat-cli sdr\\n\"",")","print","(","\"Or, in GUI mode:\\n\"",")","print","(","\" blocksat-cli sdr --gui\\n\"",")","util",".","prompt_for_enter","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L200-L271"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"_print_freq_info","parameters":"(info)","argument_list":"","return_statement":"","docstring":"Print summary of frequencies of interest","docstring_summary":"Print summary of frequencies of interest","docstring_tokens":["Print","summary","of","frequencies","of","interest"],"function":"def _print_freq_info(info):\n \"\"\"Print summary of frequencies of interest\"\"\"\n sat = info['sat']\n setup = info['setup']\n lnb = info['lnb']\n lo_freq = info['freqs']['lo']\n l_freq = info['freqs']['l_band']\n\n util.print_header(\"Frequencies\")\n\n print(\"For your information, your setup relies on the following \"\n \"frequencies:\\n\")\n print(\"| Downlink %2s band frequency | %8.2f MHz |\" %\n (sat['band'], sat['dl_freq']))\n print(\"| LNB local oscillator (LO) frequency | %8.2f MHz |\" % (lo_freq))\n print(\"| Receiver L-band frequency | %7.2f MHz |\" % (l_freq))\n print()\n\n if (lnb['universal'] and (setup['type'] == defs.sdr_setup_type)):\n if (sat['dl_freq'] > defs.ku_band_thresh):\n print(\"NOTE regarding Universal LNB:\\n\")\n\n print(\n textwrap.fill(\n (\"The DL frequency of {} is in Ku high \"\n \"band (> {:.1f} MHz). Hence, you need to use \"\n \"the higher frequency LO ({:.1f} MHz) of your \"\n \"Universal LNB. This requires a 22 kHz tone \"\n \"to be sent to the LNB.\").format(sat['alias'],\n defs.ku_band_thresh,\n lo_freq)))\n print()\n print(\n textwrap.fill((\"With a software-defined setup, you will \"\n \"need to place a 22 kHz tone generator \"\n \"inline between the LNB and the power \"\n \"inserter. Typically the tone generator \"\n \"uses power from the power inserter while \"\n \"delivering the tone directly to the \"\n \"LNB.\")))\n\n util.prompt_for_enter()","function_tokens":["def","_print_freq_info","(","info",")",":","sat","=","info","[","'sat'","]","setup","=","info","[","'setup'","]","lnb","=","info","[","'lnb'","]","lo_freq","=","info","[","'freqs'","]","[","'lo'","]","l_freq","=","info","[","'freqs'","]","[","'l_band'","]","util",".","print_header","(","\"Frequencies\"",")","print","(","\"For your information, your setup relies on the following \"","\"frequencies:\\n\"",")","print","(","\"| Downlink %2s band frequency | %8.2f MHz |\"","%","(","sat","[","'band'","]",",","sat","[","'dl_freq'","]",")",")","print","(","\"| LNB local oscillator (LO) frequency | %8.2f MHz |\"","%","(","lo_freq",")",")","print","(","\"| Receiver L-band frequency | %7.2f MHz |\"","%","(","l_freq",")",")","print","(",")","if","(","lnb","[","'universal'","]","and","(","setup","[","'type'","]","==","defs",".","sdr_setup_type",")",")",":","if","(","sat","[","'dl_freq'","]",">","defs",".","ku_band_thresh",")",":","print","(","\"NOTE regarding Universal LNB:\\n\"",")","print","(","textwrap",".","fill","(","(","\"The DL frequency of {} is in Ku high \"","\"band (> {:.1f} MHz). Hence, you need to use \"","\"the higher frequency LO ({:.1f} MHz) of your \"","\"Universal LNB. This requires a 22 kHz tone \"","\"to be sent to the LNB.\"",")",".","format","(","sat","[","'alias'","]",",","defs",".","ku_band_thresh",",","lo_freq",")",")",")","print","(",")","print","(","textwrap",".","fill","(","(","\"With a software-defined setup, you will \"","\"need to place a 22 kHz tone generator \"","\"inline between the LNB and the power \"","\"inserter. Typically the tone generator \"","\"uses power from the power inserter while \"","\"delivering the tone directly to the \"","\"LNB.\"",")",")",")","util",".","prompt_for_enter","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L328-L369"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"_print_lnb_info","parameters":"(info)","argument_list":"","return_statement":"","docstring":"Print important waraning based on LNB choice","docstring_summary":"Print important waraning based on LNB choice","docstring_tokens":["Print","important","waraning","based","on","LNB","choice"],"function":"def _print_lnb_info(info):\n \"\"\"Print important waraning based on LNB choice\"\"\"\n lnb = info['lnb']\n sat = info['sat']\n setup = info['setup']\n\n if ((lnb['pol'] != \"Dual\") and (lnb['pol'] != sat['pol'])):\n util.print_header(\"LNB Information\")\n lnb_pol = \"Vertical\" if lnb['pol'] == \"V\" else \"Horizontal\"\n logging.warning(\n textwrap.fill(\n \"Your LNB has {} polarization and the signal from {} has the \"\n \"opposite polarization.\".format(lnb_pol, sat['name'])))\n util.prompt_for_enter()\n\n if ((lnb['pol'] == \"Dual\") and (setup['type'] == defs.sdr_setup_type)):\n util.print_header(\"LNB Information\")\n logging.warning(\n textwrap.fill(\n \"Your LNB has dual polarization. Check the voltage of your \"\n \"power supply in order to discover the polarization on which \"\n \"your LNB will operate.\"))\n util.prompt_for_enter()","function_tokens":["def","_print_lnb_info","(","info",")",":","lnb","=","info","[","'lnb'","]","sat","=","info","[","'sat'","]","setup","=","info","[","'setup'","]","if","(","(","lnb","[","'pol'","]","!=","\"Dual\"",")","and","(","lnb","[","'pol'","]","!=","sat","[","'pol'","]",")",")",":","util",".","print_header","(","\"LNB Information\"",")","lnb_pol","=","\"Vertical\"","if","lnb","[","'pol'","]","==","\"V\"","else","\"Horizontal\"","logging",".","warning","(","textwrap",".","fill","(","\"Your LNB has {} polarization and the signal from {} has the \"","\"opposite polarization.\"",".","format","(","lnb_pol",",","sat","[","'name'","]",")",")",")","util",".","prompt_for_enter","(",")","if","(","(","lnb","[","'pol'","]","==","\"Dual\"",")","and","(","setup","[","'type'","]","==","defs",".","sdr_setup_type",")",")",":","util",".","print_header","(","\"LNB Information\"",")","logging",".","warning","(","textwrap",".","fill","(","\"Your LNB has dual polarization. Check the voltage of your \"","\"power supply in order to discover the polarization on which \"","\"your LNB will operate.\"",")",")","util",".","prompt_for_enter","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L372-L394"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Argument parser of instructions command","docstring_summary":"Argument parser of instructions command","docstring_tokens":["Argument","parser","of","instructions","command"],"function":"def subparser(subparsers):\n \"\"\"Argument parser of instructions command\"\"\"\n p = subparsers.add_parser('instructions',\n description=\"Instructions for Blocksat Rx setup\",\n help='Read instructions for the receiver setup',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.set_defaults(func=show)\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'instructions'",",","description","=","\"Instructions for Blocksat Rx setup\"",",","help","=","'Read instructions for the receiver setup'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","set_defaults","(","func","=","show",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L426-L433"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/instructions.py","language":"python","identifier":"show","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Show instructions","docstring_summary":"Show instructions","docstring_tokens":["Show","instructions"],"function":"def show(args):\n \"\"\"Show instructions\"\"\"\n info = config.read_cfg_file(args.cfg, args.cfg_dir)\n\n if (info is None):\n return\n\n os.system('clear')\n _print_lnb_info(info)\n\n if (info['setup']['type'] == defs.standalone_setup_type):\n _print_s400_instructions(info)\n elif (info['setup']['type'] == defs.sdr_setup_type):\n _print_sdr_instructions(info)\n elif (info['setup']['type'] == defs.linux_usb_setup_type):\n _print_usb_rx_instructions(info)\n elif (info['setup']['type'] == defs.sat_ip_setup_type):\n _print_sat_ip_instructions(info)\n\n _print_next_steps()","function_tokens":["def","show","(","args",")",":","info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","info","is","None",")",":","return","os",".","system","(","'clear'",")","_print_lnb_info","(","info",")","if","(","info","[","'setup'","]","[","'type'","]","==","defs",".","standalone_setup_type",")",":","_print_s400_instructions","(","info",")","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","sdr_setup_type",")",":","_print_sdr_instructions","(","info",")","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","linux_usb_setup_type",")",":","_print_usb_rx_instructions","(","info",")","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","sat_ip_setup_type",")",":","_print_sat_ip_instructions","(","info",")","_print_next_steps","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/instructions.py#L436-L455"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/main.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Main - parse command-line arguments and call subcommands","docstring_summary":"Main - parse command-line arguments and call subcommands","docstring_tokens":["Main","-","parse","command","-","line","arguments","and","call","subcommands"],"function":"def main():\n \"\"\"Main - parse command-line arguments and call subcommands\n \"\"\"\n default_cfg_dir = os.path.join(util.get_home_dir(), \".blocksat\")\n\n parser = ArgumentParser(\n prog=\"blocksat-cli\",\n description=\"Blockstream Satellite Command-Line Interface\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n parser.add_argument('-d',\n '--debug',\n action='store_true',\n help='Set debug mode')\n parser.add_argument('--cfg',\n default=\"config\",\n help=\"Target configuration set\")\n parser.add_argument('--cfg-dir',\n default=default_cfg_dir,\n help=\"Directory to use for configuration files\")\n parser.add_argument('--utc',\n action='store_true',\n help=\"Print log timestamps in UTC\")\n parser.add_argument('-v',\n '--version',\n action='version',\n version='%(prog)s {}'.format(__version__))\n\n subparsers = parser.add_subparsers(title='subcommands',\n help='Target sub-command',\n dest='subcommand')\n\n config.subparser(subparsers)\n instructions.subparser(subparsers)\n dependencies.subparser(subparsers)\n usb.subparser(subparsers)\n standalone.subparser(subparsers)\n rp.subparser(subparsers)\n firewall.subparser(subparsers)\n gqrx.subparser(subparsers)\n bitcoin.subparser(subparsers)\n sdr.subparser(subparsers)\n api.subparser(subparsers)\n satip.subparser(subparsers)\n\n args = parser.parse_args()\n\n # Filter commands that are Linux-only\n if (args.subcommand not in [\"cfg\", \"instructions\", \"api\", \"btc\"]):\n assert(platform.system() == 'Linux'), \\\n \"Command {} is currently Linux-only\".format(args.subcommand)\n\n # Logging\n logging_fmt = '%(asctime)s %(levelname)-8s %(name)s %(message)s' if \\\n args.debug else '%(asctime)s %(levelname)-8s %(message)s'\n logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO,\n format=logging_fmt,\n datefmt='%Y-%m-%d %H:%M:%S')\n if (args.utc):\n logging.Formatter.converter = time.gmtime\n logging.debug('[Debug Mode]')\n\n # Check CLI updates\n update.check_cli_updates(args, __version__)\n\n if hasattr(args, 'func'):\n args.func(args)\n else:\n parser.print_help()","function_tokens":["def","main","(",")",":","default_cfg_dir","=","os",".","path",".","join","(","util",".","get_home_dir","(",")",",","\".blocksat\"",")","parser","=","ArgumentParser","(","prog","=","\"blocksat-cli\"",",","description","=","\"Blockstream Satellite Command-Line Interface\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","parser",".","add_argument","(","'-d'",",","'--debug'",",","action","=","'store_true'",",","help","=","'Set debug mode'",")","parser",".","add_argument","(","'--cfg'",",","default","=","\"config\"",",","help","=","\"Target configuration set\"",")","parser",".","add_argument","(","'--cfg-dir'",",","default","=","default_cfg_dir",",","help","=","\"Directory to use for configuration files\"",")","parser",".","add_argument","(","'--utc'",",","action","=","'store_true'",",","help","=","\"Print log timestamps in UTC\"",")","parser",".","add_argument","(","'-v'",",","'--version'",",","action","=","'version'",",","version","=","'%(prog)s {}'",".","format","(","__version__",")",")","subparsers","=","parser",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",",","dest","=","'subcommand'",")","config",".","subparser","(","subparsers",")","instructions",".","subparser","(","subparsers",")","dependencies",".","subparser","(","subparsers",")","usb",".","subparser","(","subparsers",")","standalone",".","subparser","(","subparsers",")","rp",".","subparser","(","subparsers",")","firewall",".","subparser","(","subparsers",")","gqrx",".","subparser","(","subparsers",")","bitcoin",".","subparser","(","subparsers",")","sdr",".","subparser","(","subparsers",")","api",".","subparser","(","subparsers",")","satip",".","subparser","(","subparsers",")","args","=","parser",".","parse_args","(",")","# Filter commands that are Linux-only","if","(","args",".","subcommand","not","in","[","\"cfg\"",",","\"instructions\"",",","\"api\"",",","\"btc\"","]",")",":","assert","(","platform",".","system","(",")","==","'Linux'",")",",","\"Command {} is currently Linux-only\"",".","format","(","args",".","subcommand",")","# Logging","logging_fmt","=","'%(asctime)s %(levelname)-8s %(name)s %(message)s'","if","args",".","debug","else","'%(asctime)s %(levelname)-8s %(message)s'","logging",".","basicConfig","(","level","=","logging",".","DEBUG","if","args",".","debug","else","logging",".","INFO",",","format","=","logging_fmt",",","datefmt","=","'%Y-%m-%d %H:%M:%S'",")","if","(","args",".","utc",")",":","logging",".","Formatter",".","converter","=","time",".","gmtime","logging",".","debug","(","'[Debug Mode]'",")","# Check CLI updates","update",".","check_cli_updates","(","args",",","__version__",")","if","hasattr","(","args",",","'func'",")",":","args",".","func","(","args",")","else",":","parser",".","print_help","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/main.py#L16-L83"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/gqrx.py","language":"python","identifier":"configure","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Configure GQRX","docstring_summary":"Configure GQRX","docstring_tokens":["Configure","GQRX"],"function":"def configure(args):\n \"\"\"Configure GQRX\"\"\"\n info = config.read_cfg_file(args.cfg, args.cfg_dir)\n\n if (info is None):\n return\n\n util.print_header(\"Gqrx Conf Generator\")\n\n if args.path is None:\n home = os.path.expanduser(\"~\")\n path = os.path.join(home, \".config\", \"gqrx\")\n else:\n path = args.path\n\n conf_file = \"default.conf\"\n abs_path = os.path.join(path, conf_file)\n\n default_gains = r'@Variant(\\0\\0\\0\\b\\0\\0\\0\\x2\\0\\0\\0\\x6\\0L\\0N\\0\\x41\\0\\0' + \\\n r'\\0\\x2\\0\\0\\x1\\x92\\0\\0\\0\\x4\\0I\\0\\x46\\0\\0\\0\\x2\\0\\0\\0\\xcc)'\n\n cfg = \"\"\"\n [General]\n configversion=2\n\n [fft]\n averaging=80\n db_ranges_locked=true\n pandapter_min_db=-90\n waterfall_min_db=-90\n\n [input]\n bandwidth=1000000\n device=\"rtl=0\"\n frequency={}\n gains={}\n lnb_lo={}\n sample_rate=2400000\n\n [receiver]\n demod=0\n \"\"\".format(\n int(info['freqs']['dl'] * 1e6),\n default_gains,\n int(info['freqs']['lo'] * 1e6),\n )\n\n print(\"Save {} at {}\/\".format(conf_file, path))\n\n if (not util.ask_yes_or_no(\"Proceed?\")):\n print(\"Aborted\")\n return\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n if os.path.exists(abs_path):\n if (not util.ask_yes_or_no(\"File already exists. Overwrite?\")):\n print(\"Aborted\")\n return\n\n with open(abs_path, \"w\") as file:\n file.write(textwrap.dedent(cfg))\n\n print(\"Saved\")","function_tokens":["def","configure","(","args",")",":","info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","info","is","None",")",":","return","util",".","print_header","(","\"Gqrx Conf Generator\"",")","if","args",".","path","is","None",":","home","=","os",".","path",".","expanduser","(","\"~\"",")","path","=","os",".","path",".","join","(","home",",","\".config\"",",","\"gqrx\"",")","else",":","path","=","args",".","path","conf_file","=","\"default.conf\"","abs_path","=","os",".","path",".","join","(","path",",","conf_file",")","default_gains","=","r'@Variant(\\0\\0\\0\\b\\0\\0\\0\\x2\\0\\0\\0\\x6\\0L\\0N\\0\\x41\\0\\0'","+","r'\\0\\x2\\0\\0\\x1\\x92\\0\\0\\0\\x4\\0I\\0\\x46\\0\\0\\0\\x2\\0\\0\\0\\xcc)'","cfg","=","\"\"\"\n [General]\n configversion=2\n\n [fft]\n averaging=80\n db_ranges_locked=true\n pandapter_min_db=-90\n waterfall_min_db=-90\n\n [input]\n bandwidth=1000000\n device=\"rtl=0\"\n frequency={}\n gains={}\n lnb_lo={}\n sample_rate=2400000\n\n [receiver]\n demod=0\n \"\"\"",".","format","(","int","(","info","[","'freqs'","]","[","'dl'","]","*","1e6",")",",","default_gains",",","int","(","info","[","'freqs'","]","[","'lo'","]","*","1e6",")",",",")","print","(","\"Save {} at {}\/\"",".","format","(","conf_file",",","path",")",")","if","(","not","util",".","ask_yes_or_no","(","\"Proceed?\"",")",")",":","print","(","\"Aborted\"",")","return","if","not","os",".","path",".","exists","(","path",")",":","os",".","makedirs","(","path",")","if","os",".","path",".","exists","(","abs_path",")",":","if","(","not","util",".","ask_yes_or_no","(","\"File already exists. Overwrite?\"",")",")",":","print","(","\"Aborted\"",")","return","with","open","(","abs_path",",","\"w\"",")","as","file",":","file",".","write","(","textwrap",".","dedent","(","cfg",")",")","print","(","\"Saved\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/gqrx.py#L24-L88"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring._setup_registered","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Setup for a receiver that is already registered\n\n If already registered, confirm that the registered GPG key is available\n in the keyring and prompt for the GPG private key passphrase required\n to sign report data","docstring_summary":"Setup for a receiver that is already registered","docstring_tokens":["Setup","for","a","receiver","that","is","already","registered"],"function":"def _setup_registered(self):\n \"\"\"Setup for a receiver that is already registered\n\n If already registered, confirm that the registered GPG key is available\n in the keyring and prompt for the GPG private key passphrase required\n to sign report data\n\n \"\"\"\n fingerprint = self.user_info['monitoring']['fingerprint']\n matching_keys = self.gpg.gpg.list_keys(True, keys=fingerprint)\n if (len(matching_keys) == 0):\n logger.error(\"Could not find key {} in the local \"\n \"keyring.\".format(fingerprint))\n try_again = util.ask_yes_or_no(\n \"Reset the Monitoring API credentials and try registering \"\n \"with a new key?\",\n default=\"n\")\n if (try_again):\n self._delete_credentials()\n self._register()\n else:\n raise RuntimeError(\"Monitoring configuration failed\")\n\n # Return regardless. If the key is not available, don't bother\n # about the password.\n return\n self.gpg.prompt_passphrase('Please enter your GPG passphrase to '\n 'sign receiver reports: ')","function_tokens":["def","_setup_registered","(","self",")",":","fingerprint","=","self",".","user_info","[","'monitoring'","]","[","'fingerprint'","]","matching_keys","=","self",".","gpg",".","gpg",".","list_keys","(","True",",","keys","=","fingerprint",")","if","(","len","(","matching_keys",")","==","0",")",":","logger",".","error","(","\"Could not find key {} in the local \"","\"keyring.\"",".","format","(","fingerprint",")",")","try_again","=","util",".","ask_yes_or_no","(","\"Reset the Monitoring API credentials and try registering \"","\"with a new key?\"",",","default","=","\"n\"",")","if","(","try_again",")",":","self",".","_delete_credentials","(",")","self",".","_register","(",")","else",":","raise","RuntimeError","(","\"Monitoring configuration failed\"",")","# Return regardless. If the key is not available, don't bother","# about the password.","return","self",".","gpg",".","prompt_passphrase","(","'Please enter your GPG passphrase to '","'sign receiver reports: '",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L132-L159"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring._delete_credentials","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Remove the registration info from the local config file","docstring_summary":"Remove the registration info from the local config file","docstring_tokens":["Remove","the","registration","info","from","the","local","config","file"],"function":"def _delete_credentials(self):\n \"\"\"Remove the registration info from the local config file\"\"\"\n self.user_info.pop('monitoring')\n config.write_cfg_file(self.cfg, self.cfg_dir, self.user_info)\n self.registered = False","function_tokens":["def","_delete_credentials","(","self",")",":","self",".","user_info",".","pop","(","'monitoring'",")","config",".","write_cfg_file","(","self",".","cfg",",","self",".","cfg_dir",",","self",".","user_info",")","self",".","registered","=","False"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L161-L165"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring._save_credentials","parameters":"(self, uuid, fingerprint)","argument_list":"","return_statement":"","docstring":"Record the successful registration locally on the JSON config","docstring_summary":"Record the successful registration locally on the JSON config","docstring_tokens":["Record","the","successful","registration","locally","on","the","JSON","config"],"function":"def _save_credentials(self, uuid, fingerprint):\n \"\"\"Record the successful registration locally on the JSON config\"\"\"\n self.user_info['monitoring'] = {\n 'registered': True,\n 'uuid': uuid,\n 'fingerprint': fingerprint\n }\n config.write_cfg_file(self.cfg, self.cfg_dir, self.user_info)\n self.registered = True","function_tokens":["def","_save_credentials","(","self",",","uuid",",","fingerprint",")",":","self",".","user_info","[","'monitoring'","]","=","{","'registered'",":","True",",","'uuid'",":","uuid",",","'fingerprint'",":","fingerprint","}","config",".","write_cfg_file","(","self",".","cfg",",","self",".","cfg_dir",",","self",".","user_info",")","self",".","registered","=","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L167-L175"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring._register","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Run the registration procedure\n\n The procedure is divided in two steps:\n\n 1) Interaction with the user;\n 2) Interaction with the API.\n\n This method implements step 1, where it sets up a GPG keyring, collects\n the user address, and prepares the request parameters for registering\n with the monitoring API. In the end, it dispatches step 2 on a thread.\n\n Note step 2 has to run on a thread because it needs the receiver lock\n first. By running on a thread, the main (parent) thread can proceed to\n initializing the receiver.","docstring_summary":"Run the registration procedure","docstring_tokens":["Run","the","registration","procedure"],"function":"def _register(self):\n \"\"\"Run the registration procedure\n\n The procedure is divided in two steps:\n\n 1) Interaction with the user;\n 2) Interaction with the API.\n\n This method implements step 1, where it sets up a GPG keyring, collects\n the user address, and prepares the request parameters for registering\n with the monitoring API. In the end, it dispatches step 2 on a thread.\n\n Note step 2 has to run on a thread because it needs the receiver lock\n first. By running on a thread, the main (parent) thread can proceed to\n initializing the receiver.\n\n \"\"\"\n self.registration_running = True\n self.registration_failure = False\n\n # Save some state on the local cache\n cache = Cache(self.cfg_dir)\n\n # Show the explainer when running the registration for the first time\n # for this configuration\n if (cache.get(self.cfg + '.monitoring.explainer') is None):\n _register_explainer()\n\n # Cache flag indicating that the explainer has been shown already\n cache.set(self.cfg + '.monitoring.explainer', True)\n cache.save()\n\n # Create a GPG keyring and a keypair if necessary\n api.config_keyring(self.gpg)\n\n # Make sure the GPG passphrase is available. The passphrase can be\n # collected on key creation for a new keyring. On the other hand, it\n # wouldn't be available yet at this point for a pre-existing keyring.\n if (self.gpg.passphrase is None):\n util.fill_print(\"Please inform your GPG passphrase to decode the \"\n \"encrypted verification code sent over satellite\")\n self.gpg.prompt_passphrase(\"GPG passphrase: \")\n\n os.system('clear')\n\n # Get the user's location\n util.fill_print(\n \"Please inform you city, state (if applicable), and country:\")\n confirmed = False\n while (not confirmed):\n # City (required)\n city = util.string_input(\"City\")\n\n # State (optional)\n state = input(\"State: \")\n if (len(state) > 0):\n address = \"{}, {}\".format(city, state)\n else:\n address = city\n\n # Country (required)\n country = util.string_input(\"Country\")\n\n # Wait until the user confirms the full address\n address += \", {}\".format(country)\n confirmed = util.ask_yes_or_no(\"\\\"{}\\\"?\".format(address))\n\n os.system('clear')\n\n # Registration parameters\n fingerprint = self.gpg.get_default_priv_key()['fingerprint']\n pubkey = self.gpg.gpg.export_keys(fingerprint)\n satellite = self.user_info['sat']['alias']\n rx_type = config.get_rx_model(self.user_info)\n antenna = config.get_antenna_model(self.user_info)\n lnb = config.get_lnb_model(self.user_info)\n\n # Run step 2 on a thread\n t1 = threading.Thread(target=self._register_thread,\n daemon=True,\n args=(fingerprint, pubkey, address, satellite,\n rx_type, antenna, lnb))\n t1.start()","function_tokens":["def","_register","(","self",")",":","self",".","registration_running","=","True","self",".","registration_failure","=","False","# Save some state on the local cache","cache","=","Cache","(","self",".","cfg_dir",")","# Show the explainer when running the registration for the first time","# for this configuration","if","(","cache",".","get","(","self",".","cfg","+","'.monitoring.explainer'",")","is","None",")",":","_register_explainer","(",")","# Cache flag indicating that the explainer has been shown already","cache",".","set","(","self",".","cfg","+","'.monitoring.explainer'",",","True",")","cache",".","save","(",")","# Create a GPG keyring and a keypair if necessary","api",".","config_keyring","(","self",".","gpg",")","# Make sure the GPG passphrase is available. The passphrase can be","# collected on key creation for a new keyring. On the other hand, it","# wouldn't be available yet at this point for a pre-existing keyring.","if","(","self",".","gpg",".","passphrase","is","None",")",":","util",".","fill_print","(","\"Please inform your GPG passphrase to decode the \"","\"encrypted verification code sent over satellite\"",")","self",".","gpg",".","prompt_passphrase","(","\"GPG passphrase: \"",")","os",".","system","(","'clear'",")","# Get the user's location","util",".","fill_print","(","\"Please inform you city, state (if applicable), and country:\"",")","confirmed","=","False","while","(","not","confirmed",")",":","# City (required)","city","=","util",".","string_input","(","\"City\"",")","# State (optional)","state","=","input","(","\"State: \"",")","if","(","len","(","state",")",">","0",")",":","address","=","\"{}, {}\"",".","format","(","city",",","state",")","else",":","address","=","city","# Country (required)","country","=","util",".","string_input","(","\"Country\"",")","# Wait until the user confirms the full address","address","+=","\", {}\"",".","format","(","country",")","confirmed","=","util",".","ask_yes_or_no","(","\"\\\"{}\\\"?\"",".","format","(","address",")",")","os",".","system","(","'clear'",")","# Registration parameters","fingerprint","=","self",".","gpg",".","get_default_priv_key","(",")","[","'fingerprint'","]","pubkey","=","self",".","gpg",".","gpg",".","export_keys","(","fingerprint",")","satellite","=","self",".","user_info","[","'sat'","]","[","'alias'","]","rx_type","=","config",".","get_rx_model","(","self",".","user_info",")","antenna","=","config",".","get_antenna_model","(","self",".","user_info",")","lnb","=","config",".","get_lnb_model","(","self",".","user_info",")","# Run step 2 on a thread","t1","=","threading",".","Thread","(","target","=","self",".","_register_thread",",","daemon","=","True",",","args","=","(","fingerprint",",","pubkey",",","address",",","satellite",",","rx_type",",","antenna",",","lnb",")",")","t1",".","start","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L177-L259"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring._register_thread","parameters":"(self,\n fingerprint,\n pubkey,\n address,\n satellite,\n rx_type,\n antenna,\n lnb,\n attempts=5)","argument_list":"","return_statement":"","docstring":"Complete the registration procedure after receiver locking\n\n Sends the registration request to the Monitoring API and waits for the\n validation code sent over satellite through a Satellite API message.\n\n Args:\n fingerprint : User GnuPG fingerprint\n pubkey : User GnuPG public key\n address : User address\n satellite : Satellite covering the user location\n rx_type : Receiver type (vendor and model)\n antenna : Antenna type and size\n lnb : LNB model\n attempts : Maximum number of registration attempts","docstring_summary":"Complete the registration procedure after receiver locking","docstring_tokens":["Complete","the","registration","procedure","after","receiver","locking"],"function":"def _register_thread(self,\n fingerprint,\n pubkey,\n address,\n satellite,\n rx_type,\n antenna,\n lnb,\n attempts=5):\n \"\"\"Complete the registration procedure after receiver locking\n\n Sends the registration request to the Monitoring API and waits for the\n validation code sent over satellite through a Satellite API message.\n\n Args:\n fingerprint : User GnuPG fingerprint\n pubkey : User GnuPG public key\n address : User address\n satellite : Satellite covering the user location\n rx_type : Receiver type (vendor and model)\n antenna : Antenna type and size\n lnb : LNB model\n attempts : Maximum number of registration attempts\n\n \"\"\"\n logger.info(\n \"Waiting for Rx lock to initiate the registration with the \"\n \"monitoring server\")\n self.rx_lock_event.wait()\n\n logger.info(\"Receiver locked. Ready to initiate the registration with \"\n \"the monitoring server.\")\n logger.info(\"Launching the API listener to receive the verification \"\n \"code sent over satellite\")\n\n # Run the API listener loop\n #\n # Note the validation code is:\n # - Encrypted to us (the Monitoring API encrypts using our public key)\n # - Sent as a raw (non-encapsulated) API message\n # - Sent over the API channel dedicated for authentication messages\n download_dir = None # Don't save messages\n interface = config.get_net_if(self.user_info)\n recv_queue = queue.Queue() # save API donwloads on this queue\n listen_loop = ApiListener(recv_queue=recv_queue)\n listen_thread = threading.Thread(target=listen_loop.run,\n daemon=True,\n args=(self.gpg, download_dir,\n defs.api_dst_addr, interface),\n kwargs={\n 'channel': ApiChannel.AUTH.value,\n 'plaintext': False,\n 'save_raw': True,\n 'no_save': True\n })\n listen_thread.start()\n\n failure = False\n while (attempts > 0):\n rv = requests.post(account_endpoint,\n json={\n 'fingerprint': fingerprint,\n 'publickey': pubkey,\n 'city': address,\n 'satellite': satellite,\n 'receiver_type': rx_type,\n 'antenna': antenna,\n 'lnb': lnb\n })\n\n if (rv.status_code != requests.codes.ok):\n logger.error(\"Failed to register receiver with the monitoring \"\n \"server\")\n logger.error(\"{} ({})\".format(rv.reason, rv.status_code))\n\n # If the initial registration call fails, declare failure right\n # away and break the loop. The problem likely won't go away if\n # we try again (e.g., a server error or invalid pubkey).\n failure = True\n break\n\n uuid = rv.json()['uuid']\n verified = rv.json()['verified']\n\n if (verified):\n logger.info(\"Receiver already registered and verified\")\n self._save_credentials(uuid, fingerprint)\n break\n\n try:\n validation_key = recv_queue.get(timeout=10)\n recv_queue.task_done()\n except queue.Empty:\n logger.warning(\"Failed to receive the verification code. \"\n \"Trying again...\")\n attempts -= 1\n continue\n\n rv = requests.patch(account_endpoint,\n json={\n 'uuid': uuid,\n 'validation_key': validation_key.decode()\n })\n\n if (rv.status_code != requests.codes.ok):\n logger.error(\"Verification failed\")\n logger.error(\"{} ({})\".format(rv.reason, rv.status_code))\n attempts -= 1\n if (attempts > 0):\n logger.warning(\"Trying again...\")\n time.sleep(1)\n else:\n logger.info(\"Functional receiver successfully validated\")\n logger.info(\"Ready to report Rx metrics to the monitoring \"\n \"server\")\n self._save_credentials(uuid, fingerprint)\n break\n\n if (attempts == 0):\n logger.error(\"Maximum number of registration attempts \" \"reached\")\n logger.error(\"Please check if your receiver is running properly \"\n \"and restart the application to try again\")\n failure = True\n\n self.registration_running = False\n self.registration_failure = failure\n\n # Stop the API listener\n listen_loop.stop()\n listen_thread.join()","function_tokens":["def","_register_thread","(","self",",","fingerprint",",","pubkey",",","address",",","satellite",",","rx_type",",","antenna",",","lnb",",","attempts","=","5",")",":","logger",".","info","(","\"Waiting for Rx lock to initiate the registration with the \"","\"monitoring server\"",")","self",".","rx_lock_event",".","wait","(",")","logger",".","info","(","\"Receiver locked. Ready to initiate the registration with \"","\"the monitoring server.\"",")","logger",".","info","(","\"Launching the API listener to receive the verification \"","\"code sent over satellite\"",")","# Run the API listener loop","#","# Note the validation code is:","# - Encrypted to us (the Monitoring API encrypts using our public key)","# - Sent as a raw (non-encapsulated) API message","# - Sent over the API channel dedicated for authentication messages","download_dir","=","None","# Don't save messages","interface","=","config",".","get_net_if","(","self",".","user_info",")","recv_queue","=","queue",".","Queue","(",")","# save API donwloads on this queue","listen_loop","=","ApiListener","(","recv_queue","=","recv_queue",")","listen_thread","=","threading",".","Thread","(","target","=","listen_loop",".","run",",","daemon","=","True",",","args","=","(","self",".","gpg",",","download_dir",",","defs",".","api_dst_addr",",","interface",")",",","kwargs","=","{","'channel'",":","ApiChannel",".","AUTH",".","value",",","'plaintext'",":","False",",","'save_raw'",":","True",",","'no_save'",":","True","}",")","listen_thread",".","start","(",")","failure","=","False","while","(","attempts",">","0",")",":","rv","=","requests",".","post","(","account_endpoint",",","json","=","{","'fingerprint'",":","fingerprint",",","'publickey'",":","pubkey",",","'city'",":","address",",","'satellite'",":","satellite",",","'receiver_type'",":","rx_type",",","'antenna'",":","antenna",",","'lnb'",":","lnb","}",")","if","(","rv",".","status_code","!=","requests",".","codes",".","ok",")",":","logger",".","error","(","\"Failed to register receiver with the monitoring \"","\"server\"",")","logger",".","error","(","\"{} ({})\"",".","format","(","rv",".","reason",",","rv",".","status_code",")",")","# If the initial registration call fails, declare failure right","# away and break the loop. The problem likely won't go away if","# we try again (e.g., a server error or invalid pubkey).","failure","=","True","break","uuid","=","rv",".","json","(",")","[","'uuid'","]","verified","=","rv",".","json","(",")","[","'verified'","]","if","(","verified",")",":","logger",".","info","(","\"Receiver already registered and verified\"",")","self",".","_save_credentials","(","uuid",",","fingerprint",")","break","try",":","validation_key","=","recv_queue",".","get","(","timeout","=","10",")","recv_queue",".","task_done","(",")","except","queue",".","Empty",":","logger",".","warning","(","\"Failed to receive the verification code. \"","\"Trying again...\"",")","attempts","-=","1","continue","rv","=","requests",".","patch","(","account_endpoint",",","json","=","{","'uuid'",":","uuid",",","'validation_key'",":","validation_key",".","decode","(",")","}",")","if","(","rv",".","status_code","!=","requests",".","codes",".","ok",")",":","logger",".","error","(","\"Verification failed\"",")","logger",".","error","(","\"{} ({})\"",".","format","(","rv",".","reason",",","rv",".","status_code",")",")","attempts","-=","1","if","(","attempts",">","0",")",":","logger",".","warning","(","\"Trying again...\"",")","time",".","sleep","(","1",")","else",":","logger",".","info","(","\"Functional receiver successfully validated\"",")","logger",".","info","(","\"Ready to report Rx metrics to the monitoring \"","\"server\"",")","self",".","_save_credentials","(","uuid",",","fingerprint",")","break","if","(","attempts","==","0",")",":","logger",".","error","(","\"Maximum number of registration attempts \"","\"reached\"",")","logger",".","error","(","\"Please check if your receiver is running properly \"","\"and restart the application to try again\"",")","failure","=","True","self",".","registration_running","=","False","self",".","registration_failure","=","failure","# Stop the API listener","listen_loop",".","stop","(",")","listen_thread",".","join","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L261-L390"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/monitoring_api.py","language":"python","identifier":"BsMonitoring.sign_report","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Sign a dictionary of metrics to be reported to the monitoring API\n\n First, add the monitored receiver's UUID to the dictionary of\n metrics. Then, use the default local GPG privkey to generate a detached\n signature corresponding to the JSON-dumped version of the dictionary\n (including the UUID). Lastly, append the detached signature. The\n resulting dictionary (including both the UUID and the signature) is\n ready to be sent to the API.\n\n Args:\n data : Dictionary with receiver data to be reported","docstring_summary":"Sign a dictionary of metrics to be reported to the monitoring API","docstring_tokens":["Sign","a","dictionary","of","metrics","to","be","reported","to","the","monitoring","API"],"function":"def sign_report(self, data):\n \"\"\"Sign a dictionary of metrics to be reported to the monitoring API\n\n First, add the monitored receiver's UUID to the dictionary of\n metrics. Then, use the default local GPG privkey to generate a detached\n signature corresponding to the JSON-dumped version of the dictionary\n (including the UUID). Lastly, append the detached signature. The\n resulting dictionary (including both the UUID and the signature) is\n ready to be sent to the API.\n\n Args:\n data : Dictionary with receiver data to be reported\n\n \"\"\"\n assert (self.registered)\n data['uuid'] = self.user_info['monitoring']['uuid']\n fingerprint = self.user_info['monitoring']['fingerprint']\n data['signature'] = str(\n self.gpg.sign(json.dumps(data),\n fingerprint,\n clearsign=False,\n detach=True))\n if (data['signature'] == ''):\n logger.error('GPG signature failed')","function_tokens":["def","sign_report","(","self",",","data",")",":","assert","(","self",".","registered",")","data","[","'uuid'","]","=","self",".","user_info","[","'monitoring'","]","[","'uuid'","]","fingerprint","=","self",".","user_info","[","'monitoring'","]","[","'fingerprint'","]","data","[","'signature'","]","=","str","(","self",".","gpg",".","sign","(","json",".","dumps","(","data",")",",","fingerprint",",","clearsign","=","False",",","detach","=","True",")",")","if","(","data","[","'signature'","]","==","''",")",":","logger",".","error","(","'GPG signature failed'",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/monitoring_api.py#L392-L415"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_check_distro","parameters":"(setup_type)","argument_list":"","return_statement":"","docstring":"Check if distribution is supported","docstring_summary":"Check if distribution is supported","docstring_tokens":["Check","if","distribution","is","supported"],"function":"def _check_distro(setup_type):\n \"\"\"Check if distribution is supported\"\"\"\n if (distro.id() in supported_distros):\n return\n\n base_url = defs.user_guide_url + \"doc\/\"\n instructions_url = {\n defs.sdr_setup_type: \"sdr.md\",\n defs.linux_usb_setup_type: \"tbs.md\",\n defs.standalone_setup_type: \"s400.md\",\n defs.sat_ip_setup_type: \"sat-ip.md\"\n }\n full_url = base_url + instructions_url[setup_type]\n logger.error(\"{} is not a supported Linux distribution\".format(\n distro.name()))\n logger.info(\n textwrap.fill(\"Please, refer to the {} receiver setup \"\n \"instructions at {}\".format(setup_type, full_url)))\n raise ValueError(\"Unsupported Linux distribution\")","function_tokens":["def","_check_distro","(","setup_type",")",":","if","(","distro",".","id","(",")","in","supported_distros",")",":","return","base_url","=","defs",".","user_guide_url","+","\"doc\/\"","instructions_url","=","{","defs",".","sdr_setup_type",":","\"sdr.md\"",",","defs",".","linux_usb_setup_type",":","\"tbs.md\"",",","defs",".","standalone_setup_type",":","\"s400.md\"",",","defs",".","sat_ip_setup_type",":","\"sat-ip.md\"","}","full_url","=","base_url","+","instructions_url","[","setup_type","]","logger",".","error","(","\"{} is not a supported Linux distribution\"",".","format","(","distro",".","name","(",")",")",")","logger",".","info","(","textwrap",".","fill","(","\"Please, refer to the {} receiver setup \"","\"instructions at {}\"",".","format","(","setup_type",",","full_url",")",")",")","raise","ValueError","(","\"Unsupported Linux distribution\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L30-L48"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_get_apt_repo","parameters":"(distro_id)","argument_list":"","return_statement":"return apt_repo","docstring":"Find the APT package repository for the given distro","docstring_summary":"Find the APT package repository for the given distro","docstring_tokens":["Find","the","APT","package","repository","for","the","given","distro"],"function":"def _get_apt_repo(distro_id):\n \"\"\"Find the APT package repository for the given distro\"\"\"\n if distro_id == \"ubuntu\":\n apt_repo = \"ppa:blockstream\/satellite\"\n elif distro_id in [\"debian\", \"raspbian\"]:\n apt_repo = (\"https:\/\/aptly.blockstream.com\/\"\n \"satellite\/{}\/\").format(distro_id)\n else:\n raise ValueError(\"Unsupported distribution {}\".format(distro_id))\n return apt_repo","function_tokens":["def","_get_apt_repo","(","distro_id",")",":","if","distro_id","==","\"ubuntu\"",":","apt_repo","=","\"ppa:blockstream\/satellite\"","elif","distro_id","in","[","\"debian\"",",","\"raspbian\"","]",":","apt_repo","=","(","\"https:\/\/aptly.blockstream.com\/\"","\"satellite\/{}\/\"",")",".","format","(","distro_id",")","else",":","raise","ValueError","(","\"Unsupported distribution {}\"",".","format","(","distro_id",")",")","return","apt_repo"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L51-L60"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_check_pkg_repo","parameters":"(distro_id)","argument_list":"","return_statement":"return found","docstring":"Check if Blockstream Satellite's binary package repository is enabled\n\n Args:\n distro_id: Linux distribution ID\n\n Returns:\n (bool) True if the repository is already enabled","docstring_summary":"Check if Blockstream Satellite's binary package repository is enabled","docstring_tokens":["Check","if","Blockstream","Satellite","s","binary","package","repository","is","enabled"],"function":"def _check_pkg_repo(distro_id):\n \"\"\"Check if Blockstream Satellite's binary package repository is enabled\n\n Args:\n distro_id: Linux distribution ID\n\n Returns:\n (bool) True if the repository is already enabled\n\n \"\"\"\n found = False\n if (which(\"apt\")):\n apt_repo = _get_apt_repo(distro_id)\n grep_str = apt_repo.replace(\"ppa:\", \"\")\n apt_sources = glob.glob(\"\/etc\/apt\/sources.list.d\/*\")\n apt_sources.append(\"\/etc\/apt\/sources.list\")\n cmd = [\"grep\", grep_str]\n cmd.extend(apt_sources)\n res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True)\n found = (res.returncode == 0)\n elif (which(\"dnf\")):\n res = runner.run([\"dnf\", \"copr\", \"list\", \"--enabled\"],\n root=True,\n capture_output=True)\n pkgs = res.stdout.decode().splitlines()\n found = (\"copr.fedorainfracloud.org\/blockstream\/satellite\" in pkgs)\n elif (which(\"yum\")):\n yum_sources = glob.glob(\"\/etc\/yum.repos.d\/*\")\n cmd = [\"grep\", \"blockstream\/satellite\"]\n cmd.extend(yum_sources)\n res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True)\n found = (res.returncode == 0)\n else:\n raise RuntimeError(\"Could not find a supported package manager\")\n\n if (found):\n logger.debug(\"blockstream\/satellite repository already enabled\")\n\n return found","function_tokens":["def","_check_pkg_repo","(","distro_id",")",":","found","=","False","if","(","which","(","\"apt\"",")",")",":","apt_repo","=","_get_apt_repo","(","distro_id",")","grep_str","=","apt_repo",".","replace","(","\"ppa:\"",",","\"\"",")","apt_sources","=","glob",".","glob","(","\"\/etc\/apt\/sources.list.d\/*\"",")","apt_sources",".","append","(","\"\/etc\/apt\/sources.list\"",")","cmd","=","[","\"grep\"",",","grep_str","]","cmd",".","extend","(","apt_sources",")","res","=","runner",".","run","(","cmd",",","stdout","=","subprocess",".","DEVNULL",",","nocheck","=","True",")","found","=","(","res",".","returncode","==","0",")","elif","(","which","(","\"dnf\"",")",")",":","res","=","runner",".","run","(","[","\"dnf\"",",","\"copr\"",",","\"list\"",",","\"--enabled\"","]",",","root","=","True",",","capture_output","=","True",")","pkgs","=","res",".","stdout",".","decode","(",")",".","splitlines","(",")","found","=","(","\"copr.fedorainfracloud.org\/blockstream\/satellite\"","in","pkgs",")","elif","(","which","(","\"yum\"",")",")",":","yum_sources","=","glob",".","glob","(","\"\/etc\/yum.repos.d\/*\"",")","cmd","=","[","\"grep\"",",","\"blockstream\/satellite\"","]","cmd",".","extend","(","yum_sources",")","res","=","runner",".","run","(","cmd",",","stdout","=","subprocess",".","DEVNULL",",","nocheck","=","True",")","found","=","(","res",".","returncode","==","0",")","else",":","raise","RuntimeError","(","\"Could not find a supported package manager\"",")","if","(","found",")",":","logger",".","debug","(","\"blockstream\/satellite repository already enabled\"",")","return","found"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L63-L101"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_enable_pkg_repo","parameters":"(distro_id, interactive)","argument_list":"","return_statement":"","docstring":"Enable Blockstream Satellite's binary package repository\n\n Args:\n distro_id: Linux distribution ID\n interactive: Interactive mode","docstring_summary":"Enable Blockstream Satellite's binary package repository","docstring_tokens":["Enable","Blockstream","Satellite","s","binary","package","repository"],"function":"def _enable_pkg_repo(distro_id, interactive):\n \"\"\"Enable Blockstream Satellite's binary package repository\n\n Args:\n distro_id: Linux distribution ID\n interactive: Interactive mode\n\n \"\"\"\n cmds = list()\n if (which(\"apt\")):\n apt_repo = _get_apt_repo(distro_id)\n\n # On debian, add the apt repository through \"add-apt-repository\". On\n # raspbian, where \"add-apt-repository\" does not work, manually add a\n # file into \/etc\/apt\/sources.list.d\/.\n if distro_id == \"raspbian\":\n release_codename = distro.codename()\n apt_list_filename = \"blockstream-satellite-{}-{}.list\".format(\n distro_id, release_codename)\n apt_list_file = os.path.join(\"\/etc\/apt\/sources.list.d\/\",\n apt_list_filename)\n apt_component = \"main\"\n apt_file_content = \"deb {0} {1} {2}\\n# deb-src {0} {1} {2}\".format(\n apt_repo, release_codename, apt_component)\n # In execution mode, create a temporary file and move it to\n # \/etc\/apt\/sources.list.d\/. With that, only the move command needs\n # root permissions, whereas the temporary file does not. In dry-run\n # mode, print an equivalent echo command.\n if (runner.dry):\n cmd = [\n \"echo\", \"-e\",\n repr(apt_file_content), \">>\", apt_list_file\n ]\n else:\n tmp_file = tempfile.NamedTemporaryFile(mode=\"w\", delete=False)\n with tmp_file as fd:\n fd.write(apt_file_content)\n cmd = [\"mv\", tmp_file.name, apt_list_file]\n else:\n cmd = [\"add-apt-repository\", apt_repo]\n if (not interactive):\n cmd.append(\"-y\")\n\n cmds.append(cmd)\n\n if distro_id in [\"debian\", \"raspbian\"]:\n cmd = [\n \"apt-key\", \"adv\", \"--keyserver\", \"keyserver.ubuntu.com\",\n \"--recv-keys\", defs.blocksat_pubkey\n ]\n cmds.append(cmd)\n\n cmd = [\"apt\", \"update\"]\n if (not interactive):\n cmd.append(\"-y\")\n cmds.append(cmd)\n elif (which(\"dnf\")):\n cmd = [\"dnf\", \"copr\", \"enable\", \"blockstream\/satellite\"]\n if (not interactive):\n cmd.append(\"-y\")\n cmds.append(cmd)\n elif (which(\"yum\")):\n cmd = [\"yum\", \"copr\", \"enable\", \"blockstream\/satellite\"]\n if (not interactive):\n cmd.append(\"-y\")\n cmds.append(cmd)\n else:\n raise RuntimeError(\"Could not find a supported package manager\")\n\n for cmd in cmds:\n runner.run(cmd, root=True)","function_tokens":["def","_enable_pkg_repo","(","distro_id",",","interactive",")",":","cmds","=","list","(",")","if","(","which","(","\"apt\"",")",")",":","apt_repo","=","_get_apt_repo","(","distro_id",")","# On debian, add the apt repository through \"add-apt-repository\". On","# raspbian, where \"add-apt-repository\" does not work, manually add a","# file into \/etc\/apt\/sources.list.d\/.","if","distro_id","==","\"raspbian\"",":","release_codename","=","distro",".","codename","(",")","apt_list_filename","=","\"blockstream-satellite-{}-{}.list\"",".","format","(","distro_id",",","release_codename",")","apt_list_file","=","os",".","path",".","join","(","\"\/etc\/apt\/sources.list.d\/\"",",","apt_list_filename",")","apt_component","=","\"main\"","apt_file_content","=","\"deb {0} {1} {2}\\n# deb-src {0} {1} {2}\"",".","format","(","apt_repo",",","release_codename",",","apt_component",")","# In execution mode, create a temporary file and move it to","# \/etc\/apt\/sources.list.d\/. With that, only the move command needs","# root permissions, whereas the temporary file does not. In dry-run","# mode, print an equivalent echo command.","if","(","runner",".","dry",")",":","cmd","=","[","\"echo\"",",","\"-e\"",",","repr","(","apt_file_content",")",",","\">>\"",",","apt_list_file","]","else",":","tmp_file","=","tempfile",".","NamedTemporaryFile","(","mode","=","\"w\"",",","delete","=","False",")","with","tmp_file","as","fd",":","fd",".","write","(","apt_file_content",")","cmd","=","[","\"mv\"",",","tmp_file",".","name",",","apt_list_file","]","else",":","cmd","=","[","\"add-apt-repository\"",",","apt_repo","]","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","cmds",".","append","(","cmd",")","if","distro_id","in","[","\"debian\"",",","\"raspbian\"","]",":","cmd","=","[","\"apt-key\"",",","\"adv\"",",","\"--keyserver\"",",","\"keyserver.ubuntu.com\"",",","\"--recv-keys\"",",","defs",".","blocksat_pubkey","]","cmds",".","append","(","cmd",")","cmd","=","[","\"apt\"",",","\"update\"","]","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","cmds",".","append","(","cmd",")","elif","(","which","(","\"dnf\"",")",")",":","cmd","=","[","\"dnf\"",",","\"copr\"",",","\"enable\"",",","\"blockstream\/satellite\"","]","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","cmds",".","append","(","cmd",")","elif","(","which","(","\"yum\"",")",")",":","cmd","=","[","\"yum\"",",","\"copr\"",",","\"enable\"",",","\"blockstream\/satellite\"","]","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","cmds",".","append","(","cmd",")","else",":","raise","RuntimeError","(","\"Could not find a supported package manager\"",")","for","cmd","in","cmds",":","runner",".","run","(","cmd",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L104-L174"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_update_pkg_repo","parameters":"(interactive)","argument_list":"","return_statement":"","docstring":"Update APT's package index\n\n NOTE: this function updates APT only. On dnf\/yum, there is no need to run\n an update manually. The tool (dnf\/yum) updates the package index\n automatically when an install\/upgrade command is called.","docstring_summary":"Update APT's package index","docstring_tokens":["Update","APT","s","package","index"],"function":"def _update_pkg_repo(interactive):\n \"\"\"Update APT's package index\n\n NOTE: this function updates APT only. On dnf\/yum, there is no need to run\n an update manually. The tool (dnf\/yum) updates the package index\n automatically when an install\/upgrade command is called.\n\n \"\"\"\n\n if (not which(\"apt\")):\n return\n\n cmd = [\"apt\", \"update\"]\n if (not interactive):\n cmd.append(\"-y\")\n\n runner.run(cmd, root=True)","function_tokens":["def","_update_pkg_repo","(","interactive",")",":","if","(","not","which","(","\"apt\"",")",")",":","return","cmd","=","[","\"apt\"",",","\"update\"","]","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","runner",".","run","(","cmd",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L177-L193"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_install_packages","parameters":"(apt_list,\n dnf_list,\n yum_list,\n interactive=True,\n update=False)","argument_list":"","return_statement":"","docstring":"Install binary packages\n\n Args:\n apt_list : List of package names for installation via apt\n dnf_list : List of package names for installation via dnf\n dnf_list : List of package names for installation via yum\n interactive : Whether to run an interactive install (w\/ user prompting)\n update : Whether to update pre-installed packages instead","docstring_summary":"Install binary packages","docstring_tokens":["Install","binary","packages"],"function":"def _install_packages(apt_list,\n dnf_list,\n yum_list,\n interactive=True,\n update=False):\n \"\"\"Install binary packages\n\n Args:\n apt_list : List of package names for installation via apt\n dnf_list : List of package names for installation via dnf\n dnf_list : List of package names for installation via yum\n interactive : Whether to run an interactive install (w\/ user prompting)\n update : Whether to update pre-installed packages instead\n\n\n \"\"\"\n if (which(\"apt\")):\n manager = \"apt\"\n cmd = [\"apt-get\", \"install\"]\n if (update):\n cmd.append(\"--only-upgrade\")\n cmd.extend(apt_list)\n elif (which(\"dnf\")):\n manager = \"dnf\"\n if (update):\n cmd = [\"dnf\", \"upgrade\"]\n else:\n cmd = [\"dnf\", \"install\"]\n cmd.extend(dnf_list)\n elif (which(\"yum\")):\n manager = \"yum\"\n if (update):\n cmd = [\"yum\", \"upgrade\"]\n else:\n cmd = [\"yum\", \"install\"]\n cmd.extend(yum_list)\n else:\n raise RuntimeError(\"Could not find a supported package manager\")\n\n env = None\n if (not interactive):\n cmd.append(\"-y\")\n if (manager == \"apt\"):\n env = os.environ.copy()\n env[\"DEBIAN_FRONTEND\"] = \"noninteractive\"\n\n runner.run(cmd, root=True, env=env)","function_tokens":["def","_install_packages","(","apt_list",",","dnf_list",",","yum_list",",","interactive","=","True",",","update","=","False",")",":","if","(","which","(","\"apt\"",")",")",":","manager","=","\"apt\"","cmd","=","[","\"apt-get\"",",","\"install\"","]","if","(","update",")",":","cmd",".","append","(","\"--only-upgrade\"",")","cmd",".","extend","(","apt_list",")","elif","(","which","(","\"dnf\"",")",")",":","manager","=","\"dnf\"","if","(","update",")",":","cmd","=","[","\"dnf\"",",","\"upgrade\"","]","else",":","cmd","=","[","\"dnf\"",",","\"install\"","]","cmd",".","extend","(","dnf_list",")","elif","(","which","(","\"yum\"",")",")",":","manager","=","\"yum\"","if","(","update",")",":","cmd","=","[","\"yum\"",",","\"upgrade\"","]","else",":","cmd","=","[","\"yum\"",",","\"install\"","]","cmd",".","extend","(","yum_list",")","else",":","raise","RuntimeError","(","\"Could not find a supported package manager\"",")","env","=","None","if","(","not","interactive",")",":","cmd",".","append","(","\"-y\"",")","if","(","manager","==","\"apt\"",")",":","env","=","os",".","environ",".","copy","(",")","env","[","\"DEBIAN_FRONTEND\"","]","=","\"noninteractive\"","runner",".","run","(","cmd",",","root","=","True",",","env","=","env",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L196-L242"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_install_common","parameters":"(interactive=True, update=False, btc=False)","argument_list":"","return_statement":"","docstring":"Install dependencies that are common to all setups","docstring_summary":"Install dependencies that are common to all setups","docstring_tokens":["Install","dependencies","that","are","common","to","all","setups"],"function":"def _install_common(interactive=True, update=False, btc=False):\n \"\"\"Install dependencies that are common to all setups\"\"\"\n util.print_header(\"Installing Common Dependencies\")\n apt_pkg_list = [\"software-properties-common\"]\n dnf_pkg_list = [\"dnf-plugins-core\"]\n yum_pkg_list = [\"yum-plugin-copr\"]\n\n # \"gnupg\" is installed as a dependency of \"software-properties-common\" on\n # Ubuntu. In contrast, it is not a dependency on Debian. Hence, add it\n # explicitly to the list. Add also \"dirmngr\", which may not be\n # automatically installed with gnupg (it is only automatically installed\n # from buster onwards). Lastly, add \"apt-transport-https\" to fetch debian\n # and raspbian packages from Aptly using HTTPS.\n distro_id = distro.id()\n if distro_id in [\"debian\", \"raspbian\"]:\n apt_pkg_list.extend([\"gnupg\", \"dirmngr\", \"apt-transport-https\"])\n\n if distro_id == \"centos\":\n dnf_pkg_list.append(\"epel-release\")\n yum_pkg_list.append(\"epel-release\")\n\n _install_packages(apt_pkg_list, dnf_pkg_list, yum_pkg_list, interactive,\n update)\n\n # Enable our binary package repository\n if runner.dry or (not _check_pkg_repo(distro_id)):\n _enable_pkg_repo(distro_id, interactive)\n\n # Install bitcoin-satellite\n if (btc):\n apt_pkg_list = [\n \"bitcoin-satellite\", \"bitcoin-satellite-qt\", \"bitcoin-satellite-tx\"\n ]\n dnf_pkg_list = [\"bitcoin-satellite\", \"bitcoin-satellite-qt\"]\n yum_pkg_list = [\"bitcoin-satellite\", \"bitcoin-satellite-qt\"]\n\n if (which(\"dnf\")):\n # dnf matches partial package names, and so it seems that when\n # bitcoin-satellite and bitcoin-satellite-qt are installed in one\n # go, only the latter gets installed. The former is matched to\n # bitcoin-satellite-qt and assumed as installed. Hence, as a\n # workaround, install the two packages separately.\n for pkg in dnf_pkg_list:\n _install_packages(apt_pkg_list, [pkg], [pkg], interactive,\n update)\n else:\n _install_packages(apt_pkg_list, [], yum_pkg_list, interactive,\n update)","function_tokens":["def","_install_common","(","interactive","=","True",",","update","=","False",",","btc","=","False",")",":","util",".","print_header","(","\"Installing Common Dependencies\"",")","apt_pkg_list","=","[","\"software-properties-common\"","]","dnf_pkg_list","=","[","\"dnf-plugins-core\"","]","yum_pkg_list","=","[","\"yum-plugin-copr\"","]","# \"gnupg\" is installed as a dependency of \"software-properties-common\" on","# Ubuntu. In contrast, it is not a dependency on Debian. Hence, add it","# explicitly to the list. Add also \"dirmngr\", which may not be","# automatically installed with gnupg (it is only automatically installed","# from buster onwards). Lastly, add \"apt-transport-https\" to fetch debian","# and raspbian packages from Aptly using HTTPS.","distro_id","=","distro",".","id","(",")","if","distro_id","in","[","\"debian\"",",","\"raspbian\"","]",":","apt_pkg_list",".","extend","(","[","\"gnupg\"",",","\"dirmngr\"",",","\"apt-transport-https\"","]",")","if","distro_id","==","\"centos\"",":","dnf_pkg_list",".","append","(","\"epel-release\"",")","yum_pkg_list",".","append","(","\"epel-release\"",")","_install_packages","(","apt_pkg_list",",","dnf_pkg_list",",","yum_pkg_list",",","interactive",",","update",")","# Enable our binary package repository","if","runner",".","dry","or","(","not","_check_pkg_repo","(","distro_id",")",")",":","_enable_pkg_repo","(","distro_id",",","interactive",")","# Install bitcoin-satellite","if","(","btc",")",":","apt_pkg_list","=","[","\"bitcoin-satellite\"",",","\"bitcoin-satellite-qt\"",",","\"bitcoin-satellite-tx\"","]","dnf_pkg_list","=","[","\"bitcoin-satellite\"",",","\"bitcoin-satellite-qt\"","]","yum_pkg_list","=","[","\"bitcoin-satellite\"",",","\"bitcoin-satellite-qt\"","]","if","(","which","(","\"dnf\"",")",")",":","# dnf matches partial package names, and so it seems that when","# bitcoin-satellite and bitcoin-satellite-qt are installed in one","# go, only the latter gets installed. The former is matched to","# bitcoin-satellite-qt and assumed as installed. Hence, as a","# workaround, install the two packages separately.","for","pkg","in","dnf_pkg_list",":","_install_packages","(","apt_pkg_list",",","[","pkg","]",",","[","pkg","]",",","interactive",",","update",")","else",":","_install_packages","(","apt_pkg_list",",","[","]",",","yum_pkg_list",",","interactive",",","update",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L245-L292"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_install_specific","parameters":"(target, interactive=True, update=False)","argument_list":"","return_statement":"","docstring":"Install setup-specific dependencies","docstring_summary":"Install setup-specific dependencies","docstring_tokens":["Install","setup","-","specific","dependencies"],"function":"def _install_specific(target, interactive=True, update=False):\n \"\"\"Install setup-specific dependencies\"\"\"\n key = next(key for key, val in target_map.items() if val == target)\n pkg_map = {\n 'sdr': {\n 'apt': [\"gqrx-sdr\", \"rtl-sdr\", \"leandvb\", \"tsduck\"],\n 'dnf': [\"gqrx\", \"rtl-sdr\", \"leandvb\", \"tsduck\"],\n 'yum': [\"rtl-sdr\", \"leandvb\", \"tsduck\"]\n },\n 'usb': {\n 'apt': [\"iproute2\", \"iptables\", \"dvb-apps\", \"dvb-tools\"],\n 'dnf': [\"iproute\", \"iptables\", \"dvb-apps\", \"v4l-utils\"],\n 'yum': [\"iproute\", \"iptables\", \"dvb-apps\", \"v4l-utils\"]\n },\n 'standalone': {\n 'apt': [\"iproute2\", \"iptables\"],\n 'dnf': [\"iproute\", \"iptables\"],\n 'yum': [\"iproute\", \"iptables\"]\n },\n 'sat-ip': {\n 'apt': [\"iproute2\", \"tsduck\"],\n 'dnf': [\"iproute\", \"tsduck\"],\n 'yum': [\"iproute\", \"tsduck\"]\n }\n }\n # NOTE:\n # - leandvb and tsduck come from our repository. Also, note gqrx is not\n # available on CentOS (hence not included on the yum list).\n # - In the USB setup, the only package from our repository is dvb-apps in\n # the specific case of dnf (RPM) installation, given that dvb-apps is not\n # available on the latest mainstream fedora repositories.\n\n util.print_header(\"Installing {} Receiver Dependencies\".format(target))\n _install_packages(pkg_map[key]['apt'], pkg_map[key]['dnf'],\n pkg_map[key]['yum'], interactive, update)","function_tokens":["def","_install_specific","(","target",",","interactive","=","True",",","update","=","False",")",":","key","=","next","(","key","for","key",",","val","in","target_map",".","items","(",")","if","val","==","target",")","pkg_map","=","{","'sdr'",":","{","'apt'",":","[","\"gqrx-sdr\"",",","\"rtl-sdr\"",",","\"leandvb\"",",","\"tsduck\"","]",",","'dnf'",":","[","\"gqrx\"",",","\"rtl-sdr\"",",","\"leandvb\"",",","\"tsduck\"","]",",","'yum'",":","[","\"rtl-sdr\"",",","\"leandvb\"",",","\"tsduck\"","]","}",",","'usb'",":","{","'apt'",":","[","\"iproute2\"",",","\"iptables\"",",","\"dvb-apps\"",",","\"dvb-tools\"","]",",","'dnf'",":","[","\"iproute\"",",","\"iptables\"",",","\"dvb-apps\"",",","\"v4l-utils\"","]",",","'yum'",":","[","\"iproute\"",",","\"iptables\"",",","\"dvb-apps\"",",","\"v4l-utils\"","]","}",",","'standalone'",":","{","'apt'",":","[","\"iproute2\"",",","\"iptables\"","]",",","'dnf'",":","[","\"iproute\"",",","\"iptables\"","]",",","'yum'",":","[","\"iproute\"",",","\"iptables\"","]","}",",","'sat-ip'",":","{","'apt'",":","[","\"iproute2\"",",","\"tsduck\"","]",",","'dnf'",":","[","\"iproute\"",",","\"tsduck\"","]",",","'yum'",":","[","\"iproute\"",",","\"tsduck\"","]","}","}","# NOTE:","# - leandvb and tsduck come from our repository. Also, note gqrx is not","# available on CentOS (hence not included on the yum list).","# - In the USB setup, the only package from our repository is dvb-apps in","# the specific case of dnf (RPM) installation, given that dvb-apps is not","# available on the latest mainstream fedora repositories.","util",".","print_header","(","\"Installing {} Receiver Dependencies\"",".","format","(","target",")",")","_install_packages","(","pkg_map","[","key","]","[","'apt'","]",",","pkg_map","[","key","]","[","'dnf'","]",",","pkg_map","[","key","]","[","'yum'","]",",","interactive",",","update",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L295-L329"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"_print_help","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Re-create argparse's help menu","docstring_summary":"Re-create argparse's help menu","docstring_tokens":["Re","-","create","argparse","s","help","menu"],"function":"def _print_help(args):\n \"\"\"Re-create argparse's help menu\"\"\"\n parser = ArgumentParser()\n subparsers = parser.add_subparsers(title='', help='')\n parser = subparser(subparsers)\n print(parser.format_help())","function_tokens":["def","_print_help","(","args",")",":","parser","=","ArgumentParser","(",")","subparsers","=","parser",".","add_subparsers","(","title","=","''",",","help","=","''",")","parser","=","subparser","(","subparsers",")","print","(","parser",".","format_help","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L332-L337"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Parser for install command","docstring_summary":"Parser for install command","docstring_tokens":["Parser","for","install","command"],"function":"def subparser(subparsers):\n \"\"\"Parser for install command\"\"\"\n p = subparsers.add_parser('dependencies',\n aliases=['deps'],\n description=\"Manage dependencies\",\n help='Manage dependencies',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n p.set_defaults(func=_print_help)\n p.add_argument(\"-y\",\n \"--yes\",\n action='store_true',\n default=False,\n help=\"Non-interactive mode. Answers \\\"yes\\\" automatically \\\n to binary package installation prompts\")\n p.add_argument(\"--dry-run\",\n action='store_true',\n default=False,\n help=\"Print all commands but do not execute them\")\n\n subsubp = p.add_subparsers(title='subcommands', help='Target sub-command')\n\n p1 = subsubp.add_parser('install',\n description=\"Install software dependencies\",\n help='Install software dependencies')\n p1.add_argument(\"--target\",\n choices=list(target_map.keys()),\n default=None,\n help=\"Target setup type for installation of dependencies\")\n p1.add_argument(\"--btc\",\n action='store_true',\n default=False,\n help=\"Install bitcoin-satellite\")\n p1.set_defaults(func=run, update=False)\n\n p2 = subsubp.add_parser('update',\n aliases=['upgrade'],\n description=\"Update software dependencies\",\n help='Update software dependencies')\n p2.add_argument(\"--target\",\n choices=list(target_map.keys()),\n default=None,\n help=\"Target setup type for the update of dependencies\")\n p2.add_argument(\"--btc\",\n action='store_true',\n default=False,\n help=\"Update bitcoin-satellite\")\n p2.set_defaults(func=run, update=True)\n\n p3 = subsubp.add_parser('tbs-drivers',\n description=\"Install TBS USB receiver drivers\",\n help='Install TBS USB receiver drivers')\n p3.set_defaults(func=drivers)\n\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'dependencies'",",","aliases","=","[","'deps'","]",",","description","=","\"Manage dependencies\"",",","help","=","'Manage dependencies'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","set_defaults","(","func","=","_print_help",")","p",".","add_argument","(","\"-y\"",",","\"--yes\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Non-interactive mode. Answers \\\"yes\\\" automatically \\\n to binary package installation prompts\"",")","p",".","add_argument","(","\"--dry-run\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Print all commands but do not execute them\"",")","subsubp","=","p",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",")","p1","=","subsubp",".","add_parser","(","'install'",",","description","=","\"Install software dependencies\"",",","help","=","'Install software dependencies'",")","p1",".","add_argument","(","\"--target\"",",","choices","=","list","(","target_map",".","keys","(",")",")",",","default","=","None",",","help","=","\"Target setup type for installation of dependencies\"",")","p1",".","add_argument","(","\"--btc\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Install bitcoin-satellite\"",")","p1",".","set_defaults","(","func","=","run",",","update","=","False",")","p2","=","subsubp",".","add_parser","(","'update'",",","aliases","=","[","'upgrade'","]",",","description","=","\"Update software dependencies\"",",","help","=","'Update software dependencies'",")","p2",".","add_argument","(","\"--target\"",",","choices","=","list","(","target_map",".","keys","(",")",")",",","default","=","None",",","help","=","\"Target setup type for the update of dependencies\"",")","p2",".","add_argument","(","\"--btc\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Update bitcoin-satellite\"",")","p2",".","set_defaults","(","func","=","run",",","update","=","True",")","p3","=","subsubp",".","add_parser","(","'tbs-drivers'",",","description","=","\"Install TBS USB receiver drivers\"",",","help","=","'Install TBS USB receiver drivers'",")","p3",".","set_defaults","(","func","=","drivers",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L340-L394"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"run","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Run installations","docstring_summary":"Run installations","docstring_tokens":["Run","installations"],"function":"def run(args):\n \"\"\"Run installations\"\"\"\n\n # Interactive installation? I.e., requires user to press \"y\/n\"\n interactive = (not args.yes)\n\n # Configure the subprocess runner\n runner.set_dry(args.dry_run)\n\n if (args.target is not None):\n target = target_map[args.target]\n else:\n info = config.read_cfg_file(args.cfg, args.cfg_dir)\n if (info is None):\n return\n target = info['setup']['type']\n\n _check_distro(target)\n\n if (os.geteuid() != 0 and not args.dry_run):\n util.fill_print(\"Some commands require root access and may prompt \"\n \"for a password\")\n\n if (args.dry_run):\n util.print_header(\"Dry Run Mode\")\n\n # Update package index\n _update_pkg_repo(interactive)\n\n # Common dependencies (regardless of setup)\n _install_common(interactive=interactive, update=args.update, btc=args.btc)\n\n # Install setup-specific dependencies\n _install_specific(target, interactive=interactive, update=args.update)","function_tokens":["def","run","(","args",")",":","# Interactive installation? I.e., requires user to press \"y\/n\"","interactive","=","(","not","args",".","yes",")","# Configure the subprocess runner","runner",".","set_dry","(","args",".","dry_run",")","if","(","args",".","target","is","not","None",")",":","target","=","target_map","[","args",".","target","]","else",":","info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","info","is","None",")",":","return","target","=","info","[","'setup'","]","[","'type'","]","_check_distro","(","target",")","if","(","os",".","geteuid","(",")","!=","0","and","not","args",".","dry_run",")",":","util",".","fill_print","(","\"Some commands require root access and may prompt \"","\"for a password\"",")","if","(","args",".","dry_run",")",":","util",".","print_header","(","\"Dry Run Mode\"",")","# Update package index","_update_pkg_repo","(","interactive",")","# Common dependencies (regardless of setup)","_install_common","(","interactive","=","interactive",",","update","=","args",".","update",",","btc","=","args",".","btc",")","# Install setup-specific dependencies","_install_specific","(","target",",","interactive","=","interactive",",","update","=","args",".","update",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L397-L430"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/dependencies.py","language":"python","identifier":"check_apps","parameters":"(apps)","argument_list":"","return_statement":"return True","docstring":"Check if required apps are installed","docstring_summary":"Check if required apps are installed","docstring_tokens":["Check","if","required","apps","are","installed"],"function":"def check_apps(apps):\n \"\"\"Check if required apps are installed\"\"\"\n for app in apps:\n if (not which(app)):\n logging.error(\"Couldn't find {}. Is it installed?\".format(app))\n print(\"\\nTo install software dependencies, run:\")\n print(\"\"\"\n blocksat-cli deps install\n \"\"\")\n return False\n # All apps are installed\n return True","function_tokens":["def","check_apps","(","apps",")",":","for","app","in","apps",":","if","(","not","which","(","app",")",")",":","logging",".","error","(","\"Couldn't find {}. Is it installed?\"",".","format","(","app",")",")","print","(","\"\\nTo install software dependencies, run:\"",")","print","(","\"\"\"\n blocksat-cli deps install\n \"\"\"",")","return","False","# All apps are installed","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/dependencies.py#L597-L608"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.gen_args","parameters":"(self, target, btc=False)","argument_list":"","return_statement":"return parser.parse_args(args)","docstring":"Mock command-line argument","docstring_summary":"Mock command-line argument","docstring_tokens":["Mock","command","-","line","argument"],"function":"def gen_args(self, target, btc=False):\n \"\"\"Mock command-line argument\"\"\"\n logging.basicConfig(level=logging.DEBUG)\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n dependencies.subparser(subparsers)\n args = [\"deps\", \"-y\", \"install\", \"--target\", target]\n if (btc):\n args.append(\"--btc\")\n return parser.parse_args(args)","function_tokens":["def","gen_args","(","self",",","target",",","btc","=","False",")",":","logging",".","basicConfig","(","level","=","logging",".","DEBUG",")","parser","=","argparse",".","ArgumentParser","(",")","subparsers","=","parser",".","add_subparsers","(",")","dependencies",".","subparser","(","subparsers",")","args","=","[","\"deps\"",",","\"-y\"",",","\"install\"",",","\"--target\"",",","target","]","if","(","btc",")",":","args",".","append","(","\"--btc\"",")","return","parser",".","parse_args","(","args",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L8-L17"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.test_usb_deps","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Test the installation of USB receiver dependencies","docstring_summary":"Test the installation of USB receiver dependencies","docstring_tokens":["Test","the","installation","of","USB","receiver","dependencies"],"function":"def test_usb_deps(self):\n \"\"\"Test the installation of USB receiver dependencies\"\"\"\n args = self.gen_args(\"usb\")\n dependencies.run(args)\n expected_apps = [\n \"dvbnet\", \"dvb-fe-tool\", \"dvbv5-zap\", \"ip\", \"iptables\"\n ]\n self.assertTrue(dependencies.check_apps(expected_apps))","function_tokens":["def","test_usb_deps","(","self",")",":","args","=","self",".","gen_args","(","\"usb\"",")","dependencies",".","run","(","args",")","expected_apps","=","[","\"dvbnet\"",",","\"dvb-fe-tool\"",",","\"dvbv5-zap\"",",","\"ip\"",",","\"iptables\"","]","self",".","assertTrue","(","dependencies",".","check_apps","(","expected_apps",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L19-L26"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.test_sdr_deps","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Test the installation of SDR receiver dependencies","docstring_summary":"Test the installation of SDR receiver dependencies","docstring_tokens":["Test","the","installation","of","SDR","receiver","dependencies"],"function":"def test_sdr_deps(self):\n \"\"\"Test the installation of SDR receiver dependencies\"\"\"\n args = self.gen_args(\"sdr\")\n dependencies.run(args)\n expected_apps = [\"rtl_sdr\", \"leandvb\", \"ldpc_tool\", \"tsp\"]\n self.assertTrue(dependencies.check_apps(expected_apps))","function_tokens":["def","test_sdr_deps","(","self",")",":","args","=","self",".","gen_args","(","\"sdr\"",")","dependencies",".","run","(","args",")","expected_apps","=","[","\"rtl_sdr\"",",","\"leandvb\"",",","\"ldpc_tool\"",",","\"tsp\"","]","self",".","assertTrue","(","dependencies",".","check_apps","(","expected_apps",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L28-L33"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.test_standalone_deps","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Test the installation of standalone receiver dependencies","docstring_summary":"Test the installation of standalone receiver dependencies","docstring_tokens":["Test","the","installation","of","standalone","receiver","dependencies"],"function":"def test_standalone_deps(self):\n \"\"\"Test the installation of standalone receiver dependencies\"\"\"\n args = self.gen_args(\"standalone\")\n dependencies.run(args)\n expected_apps = [\"ip\", \"iptables\"]\n self.assertTrue(dependencies.check_apps(expected_apps))","function_tokens":["def","test_standalone_deps","(","self",")",":","args","=","self",".","gen_args","(","\"standalone\"",")","dependencies",".","run","(","args",")","expected_apps","=","[","\"ip\"",",","\"iptables\"","]","self",".","assertTrue","(","dependencies",".","check_apps","(","expected_apps",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L35-L40"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.test_sat_ip_deps","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Test the installation of sat-ip receiver dependencies","docstring_summary":"Test the installation of sat-ip receiver dependencies","docstring_tokens":["Test","the","installation","of","sat","-","ip","receiver","dependencies"],"function":"def test_sat_ip_deps(self):\n \"\"\"Test the installation of sat-ip receiver dependencies\"\"\"\n args = self.gen_args(\"sat-ip\")\n dependencies.run(args)\n expected_apps = [\"tsp\"]\n self.assertTrue(dependencies.check_apps(expected_apps))","function_tokens":["def","test_sat_ip_deps","(","self",")",":","args","=","self",".","gen_args","(","\"sat-ip\"",")","dependencies",".","run","(","args",")","expected_apps","=","[","\"tsp\"","]","self",".","assertTrue","(","dependencies",".","check_apps","(","expected_apps",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L42-L47"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/verify_deps_instal.py","language":"python","identifier":"TestDependencies.test_bitcoin_satellite","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Test the installation of bitcoin-satellite","docstring_summary":"Test the installation of bitcoin-satellite","docstring_tokens":["Test","the","installation","of","bitcoin","-","satellite"],"function":"def test_bitcoin_satellite(self):\n \"\"\"Test the installation of bitcoin-satellite\"\"\"\n args = self.gen_args(\"standalone\", btc=True)\n dependencies.run(args)\n expected_apps = [\"bitcoind\", \"bitcoin-cli\", \"bitcoin-tx\", \"bitcoin-qt\"]\n self.assertTrue(dependencies.check_apps(expected_apps))","function_tokens":["def","test_bitcoin_satellite","(","self",")",":","args","=","self",".","gen_args","(","\"standalone\"",",","btc","=","True",")","dependencies",".","run","(","args",")","expected_apps","=","[","\"bitcoind\"",",","\"bitcoin-cli\"",",","\"bitcoin-tx\"",",","\"bitcoin-qt\"","]","self",".","assertTrue","(","dependencies",".","check_apps","(","expected_apps",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/verify_deps_instal.py#L49-L54"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"_udpmulticast","parameters":"(dev,\n src_addr,\n dst_addr=defs.btc_dst_addr,\n trusted=\"1\",\n label=\"\")","argument_list":"","return_statement":"return dev + \",\" + dst_addr + \",\" + src_addr + \",\" + trusted + \",\" + label","docstring":"Return the udpmulticast configuration line for bitcoin.conf","docstring_summary":"Return the udpmulticast configuration line for bitcoin.conf","docstring_tokens":["Return","the","udpmulticast","configuration","line","for","bitcoin",".","conf"],"function":"def _udpmulticast(dev,\n src_addr,\n dst_addr=defs.btc_dst_addr,\n trusted=\"1\",\n label=\"\"):\n \"\"\"Return the udpmulticast configuration line for bitcoin.conf\"\"\"\n return dev + \",\" + dst_addr + \",\" + src_addr + \",\" + trusted + \",\" + label","function_tokens":["def","_udpmulticast","(","dev",",","src_addr",",","dst_addr","=","defs",".","btc_dst_addr",",","trusted","=","\"1\"",",","label","=","\"\"",")",":","return","dev","+","\",\"","+","dst_addr","+","\",\"","+","src_addr","+","\",\"","+","trusted","+","\",\"","+","label"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L54-L60"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"_gen_cfgs","parameters":"(info, interface)","argument_list":"","return_statement":"return cfg","docstring":"Generate configurations","docstring_summary":"Generate configurations","docstring_tokens":["Generate","configurations"],"function":"def _gen_cfgs(info, interface):\n \"\"\"Generate configurations\"\"\"\n cfg = Cfg()\n cfg.add_opt(\"debug\", \"udpnet\")\n cfg.add_opt(\"debug\", \"udpmulticast\")\n cfg.add_opt(\"udpmulticastloginterval\", \"600\")\n\n if (info['setup']['type'] == defs.sdr_setup_type):\n src_addr = \"127.0.0.1\"\n label = \"blocksat-sdr\"\n elif (info['setup']['type'] == defs.linux_usb_setup_type):\n src_addr = info['sat']['ip']\n label = \"blocksat-tbs\"\n elif (info['setup']['type'] == defs.standalone_setup_type):\n src_addr = info['sat']['ip']\n label = \"blocksat-s400\"\n elif (info['setup']['type'] == defs.sat_ip_setup_type):\n src_addr = \"127.0.0.1\"\n label = \"blocksat-sat-ip\"\n else:\n raise ValueError(\"Unknown setup type\")\n\n cfg.add_opt(\"udpmulticast\",\n _udpmulticast(dev=interface, src_addr=src_addr, label=label))\n\n return cfg","function_tokens":["def","_gen_cfgs","(","info",",","interface",")",":","cfg","=","Cfg","(",")","cfg",".","add_opt","(","\"debug\"",",","\"udpnet\"",")","cfg",".","add_opt","(","\"debug\"",",","\"udpmulticast\"",")","cfg",".","add_opt","(","\"udpmulticastloginterval\"",",","\"600\"",")","if","(","info","[","'setup'","]","[","'type'","]","==","defs",".","sdr_setup_type",")",":","src_addr","=","\"127.0.0.1\"","label","=","\"blocksat-sdr\"","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","linux_usb_setup_type",")",":","src_addr","=","info","[","'sat'","]","[","'ip'","]","label","=","\"blocksat-tbs\"","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","standalone_setup_type",")",":","src_addr","=","info","[","'sat'","]","[","'ip'","]","label","=","\"blocksat-s400\"","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","sat_ip_setup_type",")",":","src_addr","=","\"127.0.0.1\"","label","=","\"blocksat-sat-ip\"","else",":","raise","ValueError","(","\"Unknown setup type\"",")","cfg",".","add_opt","(","\"udpmulticast\"",",","_udpmulticast","(","dev","=","interface",",","src_addr","=","src_addr",",","label","=","label",")",")","return","cfg"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L63-L88"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return subparser","docstring":"Argument parser of bitcoin-conf command","docstring_summary":"Argument parser of bitcoin-conf command","docstring_tokens":["Argument","parser","of","bitcoin","-","conf","command"],"function":"def subparser(subparsers):\n \"\"\"Argument parser of bitcoin-conf command\"\"\"\n p = subparsers.add_parser(\n 'bitcoin-conf',\n aliases=['btc'],\n description=\"Generate Bitcoin configuration file\",\n help='Generate Bitcoin configuration file',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.add_argument('-d',\n '--datadir',\n default=None,\n help='Path to the data directory where the generated '\n 'bitcoin.conf will be saved')\n p.add_argument('--stdout',\n action='store_true',\n default=False,\n help='Print the generated bitcoin.conf file to the '\n 'standard output instead of saving the file')\n p.add_argument('--concat',\n action='store_true',\n default=False,\n help='Concatenate configurations to pre-existing '\n 'bitcoin.conf file')\n p.set_defaults(func=configure)\n\n return subparser","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'bitcoin-conf'",",","aliases","=","[","'btc'","]",",","description","=","\"Generate Bitcoin configuration file\"",",","help","=","'Generate Bitcoin configuration file'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","add_argument","(","'-d'",",","'--datadir'",",","default","=","None",",","help","=","'Path to the data directory where the generated '","'bitcoin.conf will be saved'",")","p",".","add_argument","(","'--stdout'",",","action","=","'store_true'",",","default","=","False",",","help","=","'Print the generated bitcoin.conf file to the '","'standard output instead of saving the file'",")","p",".","add_argument","(","'--concat'",",","action","=","'store_true'",",","default","=","False",",","help","=","'Concatenate configurations to pre-existing '","'bitcoin.conf file'",")","p",".","set_defaults","(","func","=","configure",")","return","subparser"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L91-L116"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"configure","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Generate bitcoin.conf configuration","docstring_summary":"Generate bitcoin.conf configuration","docstring_tokens":["Generate","bitcoin",".","conf","configuration"],"function":"def configure(args):\n \"\"\"Generate bitcoin.conf configuration\"\"\"\n info = config.read_cfg_file(args.cfg, args.cfg_dir)\n\n if (info is None):\n return\n\n if (not args.stdout):\n util.print_header(\"Bitcoin Conf Generator\")\n\n if args.datadir is None:\n home = os.path.expanduser(\"~\")\n path = os.path.join(home, \".bitcoin\")\n else:\n path = os.path.abspath(args.datadir)\n\n conf_file = \"bitcoin.conf\"\n abs_path = os.path.join(path, conf_file)\n\n # Network interface\n ifname = config.get_net_if(info)\n\n # Generate configuration object\n cfg = _gen_cfgs(info, ifname)\n\n # Load and concatenate pre-existing configurations\n if args.concat and os.path.exists(abs_path):\n with open(abs_path, \"r\") as fd:\n prev_cfg_text = fd.read()\n cfg.load_text_cfg(prev_cfg_text)\n\n # Export configurations to text format\n cfg_text = cfg.text()\n\n # Print configurations to stdout and don't save them\n if (args.stdout):\n print(cfg_text)\n return\n\n # Proceed to saving configurations\n print(\"Save {} at {}\".format(conf_file, path))\n\n if (not util.ask_yes_or_no(\"Proceed?\")):\n print(\"Aborted\")\n return\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n if os.path.exists(abs_path) and not args.concat:\n if (not util.ask_yes_or_no(\"File already exists. Overwrite?\")):\n print(\"Aborted\")\n return\n\n with open(abs_path, \"w\") as fd:\n fd.write(cfg_text)\n\n print(\"Saved\")\n\n if (info['setup']['type'] == defs.linux_usb_setup_type):\n print()\n util.fill_print(\n \"NOTE: {} was configured assuming the dvbnet interface is \"\n \"named {}. You can check if this is the case after launching the \"\n \"receiver by running:\".format(conf_file, ifname))\n print(\" ip link show | grep dvb\\n\")\n util.fill_print(\"If the dvb interfaces are numbered differently, \"\n \"please update {} accordingly.\".format(conf_file))\n elif (info['setup']['type'] == defs.standalone_setup_type):\n print(\"\\n\" + textwrap.fill(\n (\"NOTE: {0} was configured assuming the Novra S400 receiver will \"\n \"be connected to interface {1}. If this is not the case anymore, \"\n \"please update {0} accordingly.\").format(conf_file, ifname)))","function_tokens":["def","configure","(","args",")",":","info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","info","is","None",")",":","return","if","(","not","args",".","stdout",")",":","util",".","print_header","(","\"Bitcoin Conf Generator\"",")","if","args",".","datadir","is","None",":","home","=","os",".","path",".","expanduser","(","\"~\"",")","path","=","os",".","path",".","join","(","home",",","\".bitcoin\"",")","else",":","path","=","os",".","path",".","abspath","(","args",".","datadir",")","conf_file","=","\"bitcoin.conf\"","abs_path","=","os",".","path",".","join","(","path",",","conf_file",")","# Network interface","ifname","=","config",".","get_net_if","(","info",")","# Generate configuration object","cfg","=","_gen_cfgs","(","info",",","ifname",")","# Load and concatenate pre-existing configurations","if","args",".","concat","and","os",".","path",".","exists","(","abs_path",")",":","with","open","(","abs_path",",","\"r\"",")","as","fd",":","prev_cfg_text","=","fd",".","read","(",")","cfg",".","load_text_cfg","(","prev_cfg_text",")","# Export configurations to text format","cfg_text","=","cfg",".","text","(",")","# Print configurations to stdout and don't save them","if","(","args",".","stdout",")",":","print","(","cfg_text",")","return","# Proceed to saving configurations","print","(","\"Save {} at {}\"",".","format","(","conf_file",",","path",")",")","if","(","not","util",".","ask_yes_or_no","(","\"Proceed?\"",")",")",":","print","(","\"Aborted\"",")","return","if","not","os",".","path",".","exists","(","path",")",":","os",".","makedirs","(","path",")","if","os",".","path",".","exists","(","abs_path",")","and","not","args",".","concat",":","if","(","not","util",".","ask_yes_or_no","(","\"File already exists. Overwrite?\"",")",")",":","print","(","\"Aborted\"",")","return","with","open","(","abs_path",",","\"w\"",")","as","fd",":","fd",".","write","(","cfg_text",")","print","(","\"Saved\"",")","if","(","info","[","'setup'","]","[","'type'","]","==","defs",".","linux_usb_setup_type",")",":","print","(",")","util",".","fill_print","(","\"NOTE: {} was configured assuming the dvbnet interface is \"","\"named {}. You can check if this is the case after launching the \"","\"receiver by running:\"",".","format","(","conf_file",",","ifname",")",")","print","(","\" ip link show | grep dvb\\n\"",")","util",".","fill_print","(","\"If the dvb interfaces are numbered differently, \"","\"please update {} accordingly.\"",".","format","(","conf_file",")",")","elif","(","info","[","'setup'","]","[","'type'","]","==","defs",".","standalone_setup_type",")",":","print","(","\"\\n\"","+","textwrap",".","fill","(","(","\"NOTE: {0} was configured assuming the Novra S400 receiver will \"","\"be connected to interface {1}. If this is not the case anymore, \"","\"please update {0} accordingly.\"",")",".","format","(","conf_file",",","ifname",")",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L119-L191"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"Cfg.add_opt","parameters":"(self, key, val)","argument_list":"","return_statement":"","docstring":"Add key-value pair to configuration dictionary","docstring_summary":"Add key-value pair to configuration dictionary","docstring_tokens":["Add","key","-","value","pair","to","configuration","dictionary"],"function":"def add_opt(self, key, val):\n \"\"\"Add key-value pair to configuration dictionary\"\"\"\n\n # The options that appear more than once become lists on the\n # resulting dictionary.\n if (key in self.cfg):\n # If this key is not a list yet in the dictionary, make it a list\n if (not isinstance(self.cfg[key], list)):\n if (val == self.cfg[key]):\n return # identical value found\n\n new_val = list()\n new_val.append(self.cfg[key])\n new_val.append(val)\n self.cfg[key] = new_val\n else:\n if (val in self.cfg[key]):\n return # identical value found\n\n self.cfg[key].append(val)\n else:\n self.cfg[key] = val","function_tokens":["def","add_opt","(","self",",","key",",","val",")",":","# The options that appear more than once become lists on the","# resulting dictionary.","if","(","key","in","self",".","cfg",")",":","# If this key is not a list yet in the dictionary, make it a list","if","(","not","isinstance","(","self",".","cfg","[","key","]",",","list",")",")",":","if","(","val","==","self",".","cfg","[","key","]",")",":","return","# identical value found","new_val","=","list","(",")","new_val",".","append","(","self",".","cfg","[","key","]",")","new_val",".","append","(","val",")","self",".","cfg","[","key","]","=","new_val","else",":","if","(","val","in","self",".","cfg","[","key","]",")",":","return","# identical value found","self",".","cfg","[","key","]",".","append","(","val",")","else",":","self",".","cfg","[","key","]","=","val"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L12-L33"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"Cfg.load_text_cfg","parameters":"(self, text)","argument_list":"","return_statement":"","docstring":"Load configuration from text","docstring_summary":"Load configuration from text","docstring_tokens":["Load","configuration","from","text"],"function":"def load_text_cfg(self, text):\n \"\"\"Load configuration from text\"\"\"\n for line in text.splitlines():\n key = line.split(\"=\")[0]\n val = line.split(\"=\")[1]\n self.add_opt(key, val)","function_tokens":["def","load_text_cfg","(","self",",","text",")",":","for","line","in","text",".","splitlines","(",")",":","key","=","line",".","split","(","\"=\"",")","[","0","]","val","=","line",".","split","(","\"=\"",")","[","1","]","self",".","add_opt","(","key",",","val",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L35-L40"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/bitcoin.py","language":"python","identifier":"Cfg.text","parameters":"(self)","argument_list":"","return_statement":"return text","docstring":"Export configuration to text version","docstring_summary":"Export configuration to text version","docstring_tokens":["Export","configuration","to","text","version"],"function":"def text(self):\n \"\"\"Export configuration to text version\"\"\"\n text = \"\"\n for k in self.cfg:\n if (isinstance(self.cfg[k], list)):\n for e in self.cfg[k]:\n text += k + \"=\" + e + \"\\n\"\n else:\n text += k + \"=\" + self.cfg[k] + \"\\n\"\n return text","function_tokens":["def","text","(","self",")",":","text","=","\"\"","for","k","in","self",".","cfg",":","if","(","isinstance","(","self",".","cfg","[","k","]",",","list",")",")",":","for","e","in","self",".","cfg","[","k","]",":","text","+=","k","+","\"=\"","+","e","+","\"\\n\"","else",":","text","+=","k","+","\"=\"","+","self",".","cfg","[","k","]","+","\"\\n\"","return","text"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/bitcoin.py#L42-L51"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"_parse_address","parameters":"(user_info, arg_addr)","argument_list":"","return_statement":"return str(validated_addr)","docstring":"Parse the receiver's IP address","docstring_summary":"Parse the receiver's IP address","docstring_tokens":["Parse","the","receiver","s","IP","address"],"function":"def _parse_address(user_info, arg_addr):\n \"\"\"Parse the receiver's IP address\"\"\"\n # If the command-line address argument is defined, prioritize it over the\n # address configured on the JSON config file\n if (arg_addr is not None):\n raw_addr = arg_addr\n elif \"rx_ip\" in user_info[\"setup\"]:\n raw_addr = user_info[\"setup\"][\"rx_ip\"]\n else:\n raw_addr = defs.default_standalone_ip_addr\n\n try:\n validated_addr = ip_address(raw_addr)\n except ValueError:\n logger.error(\"{} is not a valid IPv4 address\".format(raw_addr))\n return\n return str(validated_addr)","function_tokens":["def","_parse_address","(","user_info",",","arg_addr",")",":","# If the command-line address argument is defined, prioritize it over the","# address configured on the JSON config file","if","(","arg_addr","is","not","None",")",":","raw_addr","=","arg_addr","elif","\"rx_ip\"","in","user_info","[","\"setup\"","]",":","raw_addr","=","user_info","[","\"setup\"","]","[","\"rx_ip\"","]","else",":","raw_addr","=","defs",".","default_standalone_ip_addr","try",":","validated_addr","=","ip_address","(","raw_addr",")","except","ValueError",":","logger",".","error","(","\"{} is not a valid IPv4 address\"",".","format","(","raw_addr",")",")","return","return","str","(","validated_addr",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L435-L451"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"cfg_standalone","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Configure the standalone receiver and the host\n\n Set all parameters required on the standalone receiver: signal, LNB, and\n MPE parameters. Then, configure the host to communicate with the the\n standalone DVB-S2 receiver by setting reverse-path filters and firewall\n configurations.","docstring_summary":"Configure the standalone receiver and the host","docstring_tokens":["Configure","the","standalone","receiver","and","the","host"],"function":"def cfg_standalone(args):\n \"\"\"Configure the standalone receiver and the host\n\n Set all parameters required on the standalone receiver: signal, LNB, and\n MPE parameters. Then, configure the host to communicate with the the\n standalone DVB-S2 receiver by setting reverse-path filters and firewall\n configurations.\n\n \"\"\"\n user_info = config.read_cfg_file(args.cfg, args.cfg_dir)\n if (user_info is None):\n return\n\n # Configure the subprocess runner\n runner.set_dry(args.dry_run)\n\n # IP Address\n rx_ip_addr = _parse_address(user_info, args.address)\n\n if (not args.rx_only):\n if 'netdev' not in user_info['setup']:\n assert(args.interface is not None), \\\n (\"Please specify the network interface through option \"\n \"\\\"-i\/--interface\\\"\")\n\n interface = args.interface if (args.interface is not None) else \\\n user_info['setup']['netdev']\n\n # Check if all dependencies are installed\n if (not dependencies.check_apps([\"iptables\"])):\n return\n\n rp.set_filters([interface], prompt=(not args.yes), dry=args.dry_run)\n firewall.configure([interface],\n defs.src_ports,\n user_info['sat']['ip'],\n igmp=True,\n prompt=(not args.yes),\n dry=args.dry_run)\n\n if (not args.host_only):\n util.print_header(\"Receiver Configuration\")\n s400 = S400Client(args.demod, rx_ip_addr, args.port, dry=args.dry_run)\n s400.configure(user_info)","function_tokens":["def","cfg_standalone","(","args",")",":","user_info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","user_info","is","None",")",":","return","# Configure the subprocess runner","runner",".","set_dry","(","args",".","dry_run",")","# IP Address","rx_ip_addr","=","_parse_address","(","user_info",",","args",".","address",")","if","(","not","args",".","rx_only",")",":","if","'netdev'","not","in","user_info","[","'setup'","]",":","assert","(","args",".","interface","is","not","None",")",",","(","\"Please specify the network interface through option \"","\"\\\"-i\/--interface\\\"\"",")","interface","=","args",".","interface","if","(","args",".","interface","is","not","None",")","else","user_info","[","'setup'","]","[","'netdev'","]","# Check if all dependencies are installed","if","(","not","dependencies",".","check_apps","(","[","\"iptables\"","]",")",")",":","return","rp",".","set_filters","(","[","interface","]",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")","firewall",".","configure","(","[","interface","]",",","defs",".","src_ports",",","user_info","[","'sat'","]","[","'ip'","]",",","igmp","=","True",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")","if","(","not","args",".","host_only",")",":","util",".","print_header","(","\"Receiver Configuration\"",")","s400","=","S400Client","(","args",".","demod",",","rx_ip_addr",",","args",".","port",",","dry","=","args",".","dry_run",")","s400",".","configure","(","user_info",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L520-L563"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"monitor","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Monitor the standalone DVB-S2 receiver","docstring_summary":"Monitor the standalone DVB-S2 receiver","docstring_tokens":["Monitor","the","standalone","DVB","-","S2","receiver"],"function":"def monitor(args):\n \"\"\"Monitor the standalone DVB-S2 receiver\"\"\"\n\n # User info\n user_info = config.read_cfg_file(args.cfg, args.cfg_dir)\n if (user_info is None):\n return\n\n # IP Address\n rx_ip_addr = _parse_address(user_info, args.address)\n\n # Client to the S400's SNMP agent\n s400 = S400Client(args.demod, rx_ip_addr, args.port)\n\n util.print_header(\"Novra S400 Receiver\")\n\n if (not s400.print_demod_config()):\n logger.error(\"s400 receiver at {} is unreachable\".format(s400.address))\n return\n\n # Log Monitoring\n monitor = monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=args.log_scrolling,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)\n\n util.print_header(\"Receiver Monitoring\")\n\n # Fetch the receiver stats periodically\n c_time = time.time()\n while (True):\n try:\n stats = s400.get_stats()\n\n if (stats is None):\n return\n\n monitor.update(stats)\n\n next_print = c_time + args.log_interval\n if (next_print > c_time):\n time.sleep(next_print - c_time)\n c_time = time.time()\n\n except KeyboardInterrupt:\n break","function_tokens":["def","monitor","(","args",")",":","# User info","user_info","=","config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","if","(","user_info","is","None",")",":","return","# IP Address","rx_ip_addr","=","_parse_address","(","user_info",",","args",".","address",")","# Client to the S400's SNMP agent","s400","=","S400Client","(","args",".","demod",",","rx_ip_addr",",","args",".","port",")","util",".","print_header","(","\"Novra S400 Receiver\"",")","if","(","not","s400",".","print_demod_config","(",")",")",":","logger",".","error","(","\"s400 receiver at {} is unreachable\"",".","format","(","s400",".","address",")",")","return","# Log Monitoring","monitor","=","monitoring",".","Monitor","(","args",".","cfg_dir",",","logfile","=","args",".","log_file",",","scroll","=","args",".","log_scrolling",",","min_interval","=","args",".","log_interval",",","server","=","args",".","monitoring_server",",","port","=","args",".","monitoring_port",",","report","=","args",".","report",",","report_opts","=","monitoring",".","get_report_opts","(","args",")",",","utc","=","args",".","utc",")","util",".","print_header","(","\"Receiver Monitoring\"",")","# Fetch the receiver stats periodically","c_time","=","time",".","time","(",")","while","(","True",")",":","try",":","stats","=","s400",".","get_stats","(",")","if","(","stats","is","None",")",":","return","monitor",".","update","(","stats",")","next_print","=","c_time","+","args",".","log_interval","if","(","next_print",">","c_time",")",":","time",".","sleep","(","next_print","-","c_time",")","c_time","=","time",".","time","(",")","except","KeyboardInterrupt",":","break"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L566-L616"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"print_help","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Re-create argparse's help menu for the standalone command","docstring_summary":"Re-create argparse's help menu for the standalone command","docstring_tokens":["Re","-","create","argparse","s","help","menu","for","the","standalone","command"],"function":"def print_help(args):\n \"\"\"Re-create argparse's help menu for the standalone command\"\"\"\n parser = ArgumentParser()\n subparsers = parser.add_subparsers(title='', help='')\n parser = subparser(subparsers)\n print(parser.format_help())","function_tokens":["def","print_help","(","args",")",":","parser","=","ArgumentParser","(",")","subparsers","=","parser",".","add_subparsers","(","title","=","''",",","help","=","''",")","parser","=","subparser","(","subparsers",")","print","(","parser",".","format_help","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L619-L624"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"SnmpClient.__init__","parameters":"(self, address, port, mib, dry=False)","argument_list":"","return_statement":"","docstring":"Constructor\n\n Args:\n address : SNMP agent's IP address\n port : SNMP agent's port\n mib : Target SNMP MIB\n dry : Dry run mode","docstring_summary":"Constructor","docstring_tokens":["Constructor"],"function":"def __init__(self, address, port, mib, dry=False):\n \"\"\"Constructor\n\n Args:\n address : SNMP agent's IP address\n port : SNMP agent's port\n mib : Target SNMP MIB\n dry : Dry run mode\n\n \"\"\"\n assert (ip_address(address)) # parse address\n self.address = address\n self.port = port\n self.mib = mib\n self.dry = dry\n self.engine = SnmpEngine()\n self._dump_mib()","function_tokens":["def","__init__","(","self",",","address",",","port",",","mib",",","dry","=","False",")",":","assert","(","ip_address","(","address",")",")","# parse address","self",".","address","=","address","self",".","port","=","port","self",".","mib","=","mib","self",".","dry","=","dry","self",".","engine","=","SnmpEngine","(",")","self",".","_dump_mib","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L62-L78"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"SnmpClient._dump_mib","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Generate the compiled (.py) MIB file","docstring_summary":"Generate the compiled (.py) MIB file","docstring_tokens":["Generate","the","compiled","(",".","py",")","MIB","file"],"function":"def _dump_mib(self):\n \"\"\"Generate the compiled (.py) MIB file\"\"\"\n\n # Check if the compiled MIB (.py file) already exists\n home = util.get_home_dir()\n self.mib_dir = mib_dir = os.path.join(home, \".pysnmp\/mibs\/\")\n if (os.path.exists(os.path.join(mib_dir, self.mib + \".py\"))):\n return\n\n cli_dir = os.path.dirname(os.path.abspath(__file__))\n mib_path = os.path.join(cli_dir, \"mib\")\n cmd = [\"mibdump.py\", \"--mib-source={}\".format(mib_path), self.mib]\n runner.run(cmd)","function_tokens":["def","_dump_mib","(","self",")",":","# Check if the compiled MIB (.py file) already exists","home","=","util",".","get_home_dir","(",")","self",".","mib_dir","=","mib_dir","=","os",".","path",".","join","(","home",",","\".pysnmp\/mibs\/\"",")","if","(","os",".","path",".","exists","(","os",".","path",".","join","(","mib_dir",",","self",".","mib","+","\".py\"",")",")",")",":","return","cli_dir","=","os",".","path",".","dirname","(","os",".","path",".","abspath","(","__file__",")",")","mib_path","=","os",".","path",".","join","(","cli_dir",",","\"mib\"",")","cmd","=","[","\"mibdump.py\"",",","\"--mib-source={}\"",".","format","(","mib_path",")",",","self",".","mib","]","runner",".","run","(","cmd",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L80-L92"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"SnmpClient._get","parameters":"(self, *variables)","argument_list":"","return_statement":"","docstring":"Get one or more variables via SNMP\n\n Args:\n Tuple with the variables to fetch via SNMP.\n\n Returns:\n List of tuples with the fetched keys and values.","docstring_summary":"Get one or more variables via SNMP","docstring_tokens":["Get","one","or","more","variables","via","SNMP"],"function":"def _get(self, *variables):\n \"\"\"Get one or more variables via SNMP\n\n Args:\n Tuple with the variables to fetch via SNMP.\n\n Returns:\n List of tuples with the fetched keys and values.\n\n \"\"\"\n obj_types = []\n for var in variables:\n if isinstance(var, tuple):\n obj = ObjectType(\n ObjectIdentity(self.mib, var[0],\n var[1]).addMibSource(self.mib_dir))\n else:\n obj = ObjectType(\n ObjectIdentity(self.mib, var,\n 0).addMibSource(self.mib_dir))\n obj_types.append(obj)\n\n errorIndication, errorStatus, errorIndex, varBinds = next(\n getCmd(self.engine, CommunityData('public'),\n UdpTransportTarget((self.address, self.port)),\n ContextData(), *obj_types))\n\n if errorIndication:\n logger.error(errorIndication)\n elif errorStatus:\n logger.error(\n '%s at %s' %\n (errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))\n else:\n res = list()\n for varBind in varBinds:\n logger.debug(' = '.join([x.prettyPrint() for x in varBind]))\n res.append(tuple([x.prettyPrint() for x in varBind]))\n return res","function_tokens":["def","_get","(","self",",","*","variables",")",":","obj_types","=","[","]","for","var","in","variables",":","if","isinstance","(","var",",","tuple",")",":","obj","=","ObjectType","(","ObjectIdentity","(","self",".","mib",",","var","[","0","]",",","var","[","1","]",")",".","addMibSource","(","self",".","mib_dir",")",")","else",":","obj","=","ObjectType","(","ObjectIdentity","(","self",".","mib",",","var",",","0",")",".","addMibSource","(","self",".","mib_dir",")",")","obj_types",".","append","(","obj",")","errorIndication",",","errorStatus",",","errorIndex",",","varBinds","=","next","(","getCmd","(","self",".","engine",",","CommunityData","(","'public'",")",",","UdpTransportTarget","(","(","self",".","address",",","self",".","port",")",")",",","ContextData","(",")",",","*","obj_types",")",")","if","errorIndication",":","logger",".","error","(","errorIndication",")","elif","errorStatus",":","logger",".","error","(","'%s at %s'","%","(","errorStatus",".","prettyPrint","(",")",",","errorIndex","and","varBinds","[","int","(","errorIndex",")","-","1","]","[","0","]","or","'?'",")",")","else",":","res","=","list","(",")","for","varBind","in","varBinds",":","logger",".","debug","(","' = '",".","join","(","[","x",".","prettyPrint","(",")","for","x","in","varBind","]",")",")","res",".","append","(","tuple","(","[","x",".","prettyPrint","(",")","for","x","in","varBind","]",")",")","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L94-L133"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"SnmpClient._set","parameters":"(self, *key_vals)","argument_list":"","return_statement":"","docstring":"Set variable via SNMP\n\n Args:\n variable : variable to set via SNMP.\n value : value to set on the given variable.","docstring_summary":"Set variable via SNMP","docstring_tokens":["Set","variable","via","SNMP"],"function":"def _set(self, *key_vals):\n \"\"\"Set variable via SNMP\n\n Args:\n variable : variable to set via SNMP.\n value : value to set on the given variable.\n\n \"\"\"\n if (self.dry):\n # Convert to the corresponding net-snmp command\n for key, val in key_vals:\n # SNMP OID\n if (isinstance(key, tuple)):\n key = \".\".join([str(x) for x in key])\n else:\n key += \".0\" # scalar values must have a .0 suffix\n # Translate values\n # TODO: Fix s400LOFrequency.0, which is not writable due to\n # being a Counter64 object.\n if (\"s400ModulationStandard\" in key):\n if (val in standard_snmp_table):\n val = standard_snmp_table[val]\n if (\"s400Modcod\" in key):\n if (val in modcod_snmp_table):\n val = modcod_snmp_table[val]\n if (\"RowStatus\" in key):\n if (val in snmp_row_status_table):\n val = snmp_row_status_table[val]\n if (val in [\"disable\", \"enable\"]):\n val = int(val == \"enable\")\n if (val in [\"disabled\", \"enabled\"]):\n val = int(val == \"enabled\")\n if (val in [\"vertical\", \"horizontal\"]):\n val = int(val == \"horizontal\")\n # Value type\n if isinstance(val, str):\n val_type = \"s\"\n elif ((\"LBandFrequency\" in key)\n or (\"SymbolRate\" in key and \"SymbolRateAuto\" not in key)\n or (\"s400MpePid1Pid\" in key)):\n val_type = \"u\"\n else:\n val_type = \"i\"\n print(\"> snmpset -v 2c -c private {}:{} {}::{} {} {}\".format(\n self.address, self.port, self.mib, key, val_type, val))\n return\n\n obj_types = []\n for key, val in key_vals:\n if isinstance(key, tuple):\n obj = ObjectType(\n ObjectIdentity(self.mib, key[0],\n key[1]).addMibSource(self.mib_dir), val)\n else:\n obj = ObjectType(\n ObjectIdentity(self.mib, key,\n 0).addMibSource(self.mib_dir), val)\n obj_types.append(obj)\n\n errorIndication, errorStatus, errorIndex, varBinds = next(\n setCmd(self.engine, CommunityData('private'),\n UdpTransportTarget((self.address, self.port), timeout=10.0),\n ContextData(), *obj_types))\n\n if errorIndication:\n logger.error(errorIndication)\n elif errorStatus:\n logger.error(\n '%s at %s' %\n (errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))\n else:\n for varBind in varBinds:\n logger.debug(' = '.join([x.prettyPrint() for x in varBind]))","function_tokens":["def","_set","(","self",",","*","key_vals",")",":","if","(","self",".","dry",")",":","# Convert to the corresponding net-snmp command","for","key",",","val","in","key_vals",":","# SNMP OID","if","(","isinstance","(","key",",","tuple",")",")",":","key","=","\".\"",".","join","(","[","str","(","x",")","for","x","in","key","]",")","else",":","key","+=","\".0\"","# scalar values must have a .0 suffix","# Translate values","# TODO: Fix s400LOFrequency.0, which is not writable due to","# being a Counter64 object.","if","(","\"s400ModulationStandard\"","in","key",")",":","if","(","val","in","standard_snmp_table",")",":","val","=","standard_snmp_table","[","val","]","if","(","\"s400Modcod\"","in","key",")",":","if","(","val","in","modcod_snmp_table",")",":","val","=","modcod_snmp_table","[","val","]","if","(","\"RowStatus\"","in","key",")",":","if","(","val","in","snmp_row_status_table",")",":","val","=","snmp_row_status_table","[","val","]","if","(","val","in","[","\"disable\"",",","\"enable\"","]",")",":","val","=","int","(","val","==","\"enable\"",")","if","(","val","in","[","\"disabled\"",",","\"enabled\"","]",")",":","val","=","int","(","val","==","\"enabled\"",")","if","(","val","in","[","\"vertical\"",",","\"horizontal\"","]",")",":","val","=","int","(","val","==","\"horizontal\"",")","# Value type","if","isinstance","(","val",",","str",")",":","val_type","=","\"s\"","elif","(","(","\"LBandFrequency\"","in","key",")","or","(","\"SymbolRate\"","in","key","and","\"SymbolRateAuto\"","not","in","key",")","or","(","\"s400MpePid1Pid\"","in","key",")",")",":","val_type","=","\"u\"","else",":","val_type","=","\"i\"","print","(","\"> snmpset -v 2c -c private {}:{} {}::{} {} {}\"",".","format","(","self",".","address",",","self",".","port",",","self",".","mib",",","key",",","val_type",",","val",")",")","return","obj_types","=","[","]","for","key",",","val","in","key_vals",":","if","isinstance","(","key",",","tuple",")",":","obj","=","ObjectType","(","ObjectIdentity","(","self",".","mib",",","key","[","0","]",",","key","[","1","]",")",".","addMibSource","(","self",".","mib_dir",")",",","val",")","else",":","obj","=","ObjectType","(","ObjectIdentity","(","self",".","mib",",","key",",","0",")",".","addMibSource","(","self",".","mib_dir",")",",","val",")","obj_types",".","append","(","obj",")","errorIndication",",","errorStatus",",","errorIndex",",","varBinds","=","next","(","setCmd","(","self",".","engine",",","CommunityData","(","'private'",")",",","UdpTransportTarget","(","(","self",".","address",",","self",".","port",")",",","timeout","=","10.0",")",",","ContextData","(",")",",","*","obj_types",")",")","if","errorIndication",":","logger",".","error","(","errorIndication",")","elif","errorStatus",":","logger",".","error","(","'%s at %s'","%","(","errorStatus",".","prettyPrint","(",")",",","errorIndex","and","varBinds","[","int","(","errorIndex",")","-","1","]","[","0","]","or","'?'",")",")","else",":","for","varBind","in","varBinds",":","logger",".","debug","(","' = '",".","join","(","[","x",".","prettyPrint","(",")","for","x","in","varBind","]",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L135-L208"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"SnmpClient._walk","parameters":"(self)","argument_list":"","return_statement":"return res","docstring":"SNMP Walk\n\n Returns:\n Dictionary with configurations fetched via SNMP.","docstring_summary":"SNMP Walk","docstring_tokens":["SNMP","Walk"],"function":"def _walk(self):\n \"\"\"SNMP Walk\n\n Returns:\n Dictionary with configurations fetched via SNMP.\n\n \"\"\"\n iterator = nextCmd(\n self.engine, CommunityData('public'),\n UdpTransportTarget((self.address, self.port)), ContextData(),\n ObjectType(\n ObjectIdentity(self.mib, '', 0).addMibSource(self.mib_dir)))\n res = {}\n for errorIndication, errorStatus, errorIndex, varBinds in iterator:\n if errorIndication:\n logger.error(errorIndication)\n elif errorStatus:\n logger.error(\n '%s at %s' %\n (errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))\n else:\n for varBind in varBinds:\n logger.debug(varBind)\n varBindList = [x.prettyPrint() for x in varBind]\n key = varBindList[0].replace(self.mib + \"::\", \"\")\n if (len(varBindList) > 2):\n res[key] = tuple(varBindList[1:])\n else:\n res[key] = varBindList[1]\n return res","function_tokens":["def","_walk","(","self",")",":","iterator","=","nextCmd","(","self",".","engine",",","CommunityData","(","'public'",")",",","UdpTransportTarget","(","(","self",".","address",",","self",".","port",")",")",",","ContextData","(",")",",","ObjectType","(","ObjectIdentity","(","self",".","mib",",","''",",","0",")",".","addMibSource","(","self",".","mib_dir",")",")",")","res","=","{","}","for","errorIndication",",","errorStatus",",","errorIndex",",","varBinds","in","iterator",":","if","errorIndication",":","logger",".","error","(","errorIndication",")","elif","errorStatus",":","logger",".","error","(","'%s at %s'","%","(","errorStatus",".","prettyPrint","(",")",",","errorIndex","and","varBinds","[","int","(","errorIndex",")","-","1","]","[","0","]","or","'?'",")",")","else",":","for","varBind","in","varBinds",":","logger",".","debug","(","varBind",")","varBindList","=","[","x",".","prettyPrint","(",")","for","x","in","varBind","]","key","=","varBindList","[","0","]",".","replace","(","self",".","mib","+","\"::\"",",","\"\"",")","if","(","len","(","varBindList",")",">","2",")",":","res","[","key","]","=","tuple","(","varBindList","[","1",":","]",")","else",":","res","[","key","]","=","varBindList","[","1","]","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L210-L240"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"S400Client.get_stats","parameters":"(self)","argument_list":"","return_statement":"return stats","docstring":"Get demodulator statistics\n\n Returns:\n Dictionary with the receiver stats following the format expected by\n the Monitor class (from monitor.py), i.e., each dictionary element\n as a tuple \"(value, unit)\".","docstring_summary":"Get demodulator statistics","docstring_tokens":["Get","demodulator","statistics"],"function":"def get_stats(self):\n \"\"\"Get demodulator statistics\n\n Returns:\n Dictionary with the receiver stats following the format expected by\n the Monitor class (from monitor.py), i.e., each dictionary element\n as a tuple \"(value, unit)\".\n\n \"\"\"\n res = self._get('s400SignalLockStatus' + self.demod,\n 's400SignalStrength' + self.demod,\n 's400CarrierToNoise' + self.demod,\n 's400UncorrectedPackets' + self.demod,\n 's400BER' + self.demod)\n\n if res is None:\n return\n\n signal_lock_raw = res[0][1]\n signal_raw = res[1][1]\n c_to_n_raw = res[2][1]\n uncorr_raw = res[3][1]\n ber_raw = res[4][1]\n\n # Parse\n signal_lock = (signal_lock_raw == 'locked')\n stats = {'lock': (signal_lock, None)}\n\n # Metrics that require locking\n #\n # NOTE: the S400 does not return the signal level if unlocked.\n if (signal_lock):\n level = float('nan') if (signal_raw\n == '< 70') else float(signal_raw)\n cnr = float('nan') if (c_to_n_raw == '< 3') else float(c_to_n_raw)\n stats['snr'] = (cnr, \"dB\")\n stats['level'] = (level, \"dBm\")\n stats['ber'] = (float(ber_raw), None)\n stats['pkt_err'] = (int(uncorr_raw), None)\n\n return stats","function_tokens":["def","get_stats","(","self",")",":","res","=","self",".","_get","(","'s400SignalLockStatus'","+","self",".","demod",",","'s400SignalStrength'","+","self",".","demod",",","'s400CarrierToNoise'","+","self",".","demod",",","'s400UncorrectedPackets'","+","self",".","demod",",","'s400BER'","+","self",".","demod",")","if","res","is","None",":","return","signal_lock_raw","=","res","[","0","]","[","1","]","signal_raw","=","res","[","1","]","[","1","]","c_to_n_raw","=","res","[","2","]","[","1","]","uncorr_raw","=","res","[","3","]","[","1","]","ber_raw","=","res","[","4","]","[","1","]","# Parse","signal_lock","=","(","signal_lock_raw","==","'locked'",")","stats","=","{","'lock'",":","(","signal_lock",",","None",")","}","# Metrics that require locking","#","# NOTE: the S400 does not return the signal level if unlocked.","if","(","signal_lock",")",":","level","=","float","(","'nan'",")","if","(","signal_raw","==","'< 70'",")","else","float","(","signal_raw",")","cnr","=","float","(","'nan'",")","if","(","c_to_n_raw","==","'< 3'",")","else","float","(","c_to_n_raw",")","stats","[","'snr'","]","=","(","cnr",",","\"dB\"",")","stats","[","'level'","]","=","(","level",",","\"dBm\"",")","stats","[","'ber'","]","=","(","float","(","ber_raw",")",",","None",")","stats","[","'pkt_err'","]","=","(","int","(","uncorr_raw",")",",","None",")","return","stats"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L249-L289"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"S400Client.print_demod_config","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Get demodulator configurations via SNMP\n\n Returns:\n Bool indicating whether the demodulator configurations were printed\n successfully.","docstring_summary":"Get demodulator configurations via SNMP","docstring_tokens":["Get","demodulator","configurations","via","SNMP"],"function":"def print_demod_config(self):\n \"\"\"Get demodulator configurations via SNMP\n\n Returns:\n Bool indicating whether the demodulator configurations were printed\n successfully.\n\n \"\"\"\n res = self._get(\n 's400FirmwareVersion',\n # Demodulator\n 's400ModulationStandard' + self.demod,\n 's400LBandFrequency' + self.demod,\n 's400SymbolRate' + self.demod,\n 's400Modcod' + self.demod,\n # LNB\n 's400LNBSupply',\n 's400LOFrequency',\n 's400Polarization',\n 's400Enable22KHzTone',\n 's400LongLineCompensation',\n # MPE\n ('s400MpePid1Pid', 0),\n ('s400MpePid1Pid', 1),\n ('s400MpePid1RowStatus', 0),\n ('s400MpePid1RowStatus', 1))\n\n if (res is None):\n return False\n\n # Form dictionary with the S400 configs\n cfg = {}\n for res in res:\n key = res[0].replace('NOVRA-s400-MIB::s400', '')\n val = res[1]\n cfg[key] = val\n\n # Map dictionary to more informative labels\n demod_label_map = {\n 'ModulationStandard' + self.demod + '.0': \"Standard\",\n 'LBandFrequency' + self.demod + '.0': \"L-band Frequency\",\n 'SymbolRate' + self.demod + '.0': \"Symbol Rate\",\n 'Modcod' + self.demod + '.0': \"MODCOD\",\n }\n lnb_label_map = {\n 'LNBSupply.0': \"LNB Power Supply\",\n 'LOFrequency.0': \"LO Frequency\",\n 'Polarization.0': \"Polarization\",\n 'Enable22KHzTone.0': \"22 kHz Tone\",\n 'LongLineCompensation.0': \"Long Line Compensation\"\n }\n mpe_label_map = {\n 'MpePid1Pid.0': \"MPE PID\",\n 'MpePid1RowStatus.0': \"MPE PID Status\"\n }\n label_map = {\n \"Demodulator\": demod_label_map,\n \"LNB Options\": lnb_label_map,\n \"MPE Options\": mpe_label_map\n }\n\n print(\"Firmware Version: {}\".format(cfg['FirmwareVersion.0']))\n for map_key in label_map:\n print(\"{}:\".format(map_key))\n for key in cfg:\n if key in label_map[map_key]:\n label = label_map[map_key][key]\n if (label == \"MODCOD\"):\n val = \"VCM\" if cfg[key] == \"31\" else cfg[key]\n elif (label == \"Standard\"):\n val = cfg[key].upper()\n else:\n val = cfg[key]\n print(\"- {}: {}\".format(label, val))\n return True","function_tokens":["def","print_demod_config","(","self",")",":","res","=","self",".","_get","(","'s400FirmwareVersion'",",","# Demodulator","'s400ModulationStandard'","+","self",".","demod",",","'s400LBandFrequency'","+","self",".","demod",",","'s400SymbolRate'","+","self",".","demod",",","'s400Modcod'","+","self",".","demod",",","# LNB","'s400LNBSupply'",",","'s400LOFrequency'",",","'s400Polarization'",",","'s400Enable22KHzTone'",",","'s400LongLineCompensation'",",","# MPE","(","'s400MpePid1Pid'",",","0",")",",","(","'s400MpePid1Pid'",",","1",")",",","(","'s400MpePid1RowStatus'",",","0",")",",","(","'s400MpePid1RowStatus'",",","1",")",")","if","(","res","is","None",")",":","return","False","# Form dictionary with the S400 configs","cfg","=","{","}","for","res","in","res",":","key","=","res","[","0","]",".","replace","(","'NOVRA-s400-MIB::s400'",",","''",")","val","=","res","[","1","]","cfg","[","key","]","=","val","# Map dictionary to more informative labels","demod_label_map","=","{","'ModulationStandard'","+","self",".","demod","+","'.0'",":","\"Standard\"",",","'LBandFrequency'","+","self",".","demod","+","'.0'",":","\"L-band Frequency\"",",","'SymbolRate'","+","self",".","demod","+","'.0'",":","\"Symbol Rate\"",",","'Modcod'","+","self",".","demod","+","'.0'",":","\"MODCOD\"",",","}","lnb_label_map","=","{","'LNBSupply.0'",":","\"LNB Power Supply\"",",","'LOFrequency.0'",":","\"LO Frequency\"",",","'Polarization.0'",":","\"Polarization\"",",","'Enable22KHzTone.0'",":","\"22 kHz Tone\"",",","'LongLineCompensation.0'",":","\"Long Line Compensation\"","}","mpe_label_map","=","{","'MpePid1Pid.0'",":","\"MPE PID\"",",","'MpePid1RowStatus.0'",":","\"MPE PID Status\"","}","label_map","=","{","\"Demodulator\"",":","demod_label_map",",","\"LNB Options\"",":","lnb_label_map",",","\"MPE Options\"",":","mpe_label_map","}","print","(","\"Firmware Version: {}\"",".","format","(","cfg","[","'FirmwareVersion.0'","]",")",")","for","map_key","in","label_map",":","print","(","\"{}:\"",".","format","(","map_key",")",")","for","key","in","cfg",":","if","key","in","label_map","[","map_key","]",":","label","=","label_map","[","map_key","]","[","key","]","if","(","label","==","\"MODCOD\"",")",":","val","=","\"VCM\"","if","cfg","[","key","]","==","\"31\"","else","cfg","[","key","]","elif","(","label","==","\"Standard\"",")",":","val","=","cfg","[","key","]",".","upper","(",")","else",":","val","=","cfg","[","key","]","print","(","\"- {}: {}\"",".","format","(","label",",","val",")",")","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L291-L365"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/standalone.py","language":"python","identifier":"S400Client.configure","parameters":"(self, info)","argument_list":"","return_statement":"","docstring":"Configure the S400","docstring_summary":"Configure the S400","docstring_tokens":["Configure","the","S400"],"function":"def configure(self, info):\n \"\"\"Configure the S400\"\"\"\n logger.info(\"Configuring the S400 receiver at {} via SNMP\".format(\n self.address))\n\n # Local parameters\n l_band_freq = int(info['freqs']['l_band'] * 1e6)\n lo_freq = int(info['freqs']['lo'] * 1e6)\n sym_rate = defs.sym_rate[info['sat']['alias']]\n if (info['lnb']['pol'].lower() == \"dual\"\n and 'v1_pointed' in info['lnb'] and info['lnb']['v1_pointed']):\n pol = \"horizontal\" if (info['lnb'][\"v1_psu_voltage\"] >= 16) else \\\n \"vertical\"\n else:\n pol = \"horizontal\" if (info['sat']['pol'] == \"H\") else \"vertical\"\n if (info['lnb']['universal']\n and info['freqs']['dl'] > defs.ku_band_thresh):\n tone = 'enable'\n else:\n tone = 'disable'\n\n # Fetch and delete the current MPE PIDs\n current_cfg = self._walk()\n mpe_prefix = 's400MpePid' + self.demod\n has_mpe_table = any(\n [mpe_prefix + \"RowStatus\" in key for key in current_cfg])\n if (has_mpe_table):\n logger.info(\"Resetting MPE PIDs\")\n for key in current_cfg:\n mpe_row_status = mpe_prefix + \"RowStatus\"\n if mpe_row_status in key:\n self._set((tuple(key.split(\".\")), 'destroy'))\n\n # Configure via SNMP\n logger.info(\"Configuring interface RF{}\".format(self.demod))\n self._set(('s400ModulationStandard' + self.demod, 'dvbs2'))\n self._set(('s400LBandFrequency' + self.demod, l_band_freq))\n self._set(('s400SymbolRate' + self.demod, sym_rate))\n self._set(('s400SymbolRateAuto' + self.demod, 'disable'))\n\n logger.info(\"Setting LNB parameters\")\n self._set(('s400LOFrequency', lo_freq))\n self._set(('s400Polarization', pol))\n self._set(('s400LongLineCompensation', 'disable'))\n\n logger.info(\"Configuring the RF{} service\".format(self.demod))\n self._set(('s400Modcod' + self.demod, 'auto'))\n self._set(('s400ForwardEntireStream' + self.demod, 'disable'))\n\n # Set the target PIDs\n for i_pid, pid in enumerate(defs.pids):\n logger.info(\"Adding MPE PID {}\".format(pid))\n self._set((('s400MpePid' + self.demod + 'RowStatus', i_pid),\n 'createAndWait'))\n self._set((('s400MpePid' + self.demod + 'Pid', i_pid), pid))\n self._set(\n (('s400MpePid' + self.demod + 'RowStatus', i_pid), 'active'))\n\n logger.info(\"Turning on the LNB power\")\n self._set(('s400LNBSupply', 'enabled'))\n if (tone == 'enable'):\n logger.info(\"Enabling the LNB 22kHz tone\")\n self._set(('s400Enable22KHzTone', tone))\n\n if (not self.dry):\n logger.info(\"Receiver configured successfully\")","function_tokens":["def","configure","(","self",",","info",")",":","logger",".","info","(","\"Configuring the S400 receiver at {} via SNMP\"",".","format","(","self",".","address",")",")","# Local parameters","l_band_freq","=","int","(","info","[","'freqs'","]","[","'l_band'","]","*","1e6",")","lo_freq","=","int","(","info","[","'freqs'","]","[","'lo'","]","*","1e6",")","sym_rate","=","defs",".","sym_rate","[","info","[","'sat'","]","[","'alias'","]","]","if","(","info","[","'lnb'","]","[","'pol'","]",".","lower","(",")","==","\"dual\"","and","'v1_pointed'","in","info","[","'lnb'","]","and","info","[","'lnb'","]","[","'v1_pointed'","]",")",":","pol","=","\"horizontal\"","if","(","info","[","'lnb'","]","[","\"v1_psu_voltage\"","]",">=","16",")","else","\"vertical\"","else",":","pol","=","\"horizontal\"","if","(","info","[","'sat'","]","[","'pol'","]","==","\"H\"",")","else","\"vertical\"","if","(","info","[","'lnb'","]","[","'universal'","]","and","info","[","'freqs'","]","[","'dl'","]",">","defs",".","ku_band_thresh",")",":","tone","=","'enable'","else",":","tone","=","'disable'","# Fetch and delete the current MPE PIDs","current_cfg","=","self",".","_walk","(",")","mpe_prefix","=","'s400MpePid'","+","self",".","demod","has_mpe_table","=","any","(","[","mpe_prefix","+","\"RowStatus\"","in","key","for","key","in","current_cfg","]",")","if","(","has_mpe_table",")",":","logger",".","info","(","\"Resetting MPE PIDs\"",")","for","key","in","current_cfg",":","mpe_row_status","=","mpe_prefix","+","\"RowStatus\"","if","mpe_row_status","in","key",":","self",".","_set","(","(","tuple","(","key",".","split","(","\".\"",")",")",",","'destroy'",")",")","# Configure via SNMP","logger",".","info","(","\"Configuring interface RF{}\"",".","format","(","self",".","demod",")",")","self",".","_set","(","(","'s400ModulationStandard'","+","self",".","demod",",","'dvbs2'",")",")","self",".","_set","(","(","'s400LBandFrequency'","+","self",".","demod",",","l_band_freq",")",")","self",".","_set","(","(","'s400SymbolRate'","+","self",".","demod",",","sym_rate",")",")","self",".","_set","(","(","'s400SymbolRateAuto'","+","self",".","demod",",","'disable'",")",")","logger",".","info","(","\"Setting LNB parameters\"",")","self",".","_set","(","(","'s400LOFrequency'",",","lo_freq",")",")","self",".","_set","(","(","'s400Polarization'",",","pol",")",")","self",".","_set","(","(","'s400LongLineCompensation'",",","'disable'",")",")","logger",".","info","(","\"Configuring the RF{} service\"",".","format","(","self",".","demod",")",")","self",".","_set","(","(","'s400Modcod'","+","self",".","demod",",","'auto'",")",")","self",".","_set","(","(","'s400ForwardEntireStream'","+","self",".","demod",",","'disable'",")",")","# Set the target PIDs","for","i_pid",",","pid","in","enumerate","(","defs",".","pids",")",":","logger",".","info","(","\"Adding MPE PID {}\"",".","format","(","pid",")",")","self",".","_set","(","(","(","'s400MpePid'","+","self",".","demod","+","'RowStatus'",",","i_pid",")",",","'createAndWait'",")",")","self",".","_set","(","(","(","'s400MpePid'","+","self",".","demod","+","'Pid'",",","i_pid",")",",","pid",")",")","self",".","_set","(","(","(","'s400MpePid'","+","self",".","demod","+","'RowStatus'",",","i_pid",")",",","'active'",")",")","logger",".","info","(","\"Turning on the LNB power\"",")","self",".","_set","(","(","'s400LNBSupply'",",","'enabled'",")",")","if","(","tone","==","'enable'",")",":","logger",".","info","(","\"Enabling the LNB 22kHz tone\"",")","self",".","_set","(","(","'s400Enable22KHzTone'",",","tone",")",")","if","(","not","self",".","dry",")",":","logger",".","info","(","\"Receiver configured successfully\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/standalone.py#L367-L432"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_find_v4l_lnb","parameters":"(info)","argument_list":"","return_statement":"return options[0]","docstring":"Find suitable LNB within v4l-utils preset LNBs\n\n The LNBs on list v4l_lnbs are defined at lib\/libdvbv5\/dvb-sat.c","docstring_summary":"Find suitable LNB within v4l-utils preset LNBs","docstring_tokens":["Find","suitable","LNB","within","v4l","-","utils","preset","LNBs"],"function":"def _find_v4l_lnb(info):\n \"\"\"Find suitable LNB within v4l-utils preset LNBs\n\n The LNBs on list v4l_lnbs are defined at lib\/libdvbv5\/dvb-sat.c\n\n \"\"\"\n\n target_lo_freq_raw = info['lnb']['lo_freq']\n target_is_universal = info['lnb']['universal']\n\n if (target_is_universal):\n assert (isinstance(target_lo_freq_raw, list))\n assert (len(target_lo_freq_raw) == 2)\n target_lo_freq = [int(x) for x in target_lo_freq_raw]\n else:\n target_lo_freq = [int(target_lo_freq_raw)]\n\n # Find options that match the LO freq\n options = list()\n for lnb in defs.v4l_lnbs:\n is_universal_option = 'highfreq' in lnb\n\n if (target_is_universal and (not is_universal_option)):\n continue\n\n if (info['lnb']['pol'].lower() == \"dual\" and # user has dual-pol LNB\n (\n info['sat']['pol'] == \"H\" or # and satellite requires H pol\n (\n 'v1_pointed' in info['lnb'] and info['lnb']['v1_pointed']\n and info['lnb']['v1_psu_voltage'] >=\n 16 # or LNB already operates with H pol\n )) and \"rangeswitch\"\n not in lnb): # but LNB candidate is single-pol\n continue # not a validate candidate, skip\n\n if (target_is_universal):\n if (is_universal_option and lnb['lowfreq'] == target_lo_freq[0]\n and lnb['highfreq'] == target_lo_freq[1]):\n options.append(lnb)\n else:\n if (lnb['lowfreq'] == target_lo_freq[0]):\n options.append(lnb)\n\n assert (len(options) > 0), \"LNB doesn't match a valid option\"\n logger.debug(\"Matching LNB options: {}\".format(pformat(options)))\n\n return options[0]","function_tokens":["def","_find_v4l_lnb","(","info",")",":","target_lo_freq_raw","=","info","[","'lnb'","]","[","'lo_freq'","]","target_is_universal","=","info","[","'lnb'","]","[","'universal'","]","if","(","target_is_universal",")",":","assert","(","isinstance","(","target_lo_freq_raw",",","list",")",")","assert","(","len","(","target_lo_freq_raw",")","==","2",")","target_lo_freq","=","[","int","(","x",")","for","x","in","target_lo_freq_raw","]","else",":","target_lo_freq","=","[","int","(","target_lo_freq_raw",")","]","# Find options that match the LO freq","options","=","list","(",")","for","lnb","in","defs",".","v4l_lnbs",":","is_universal_option","=","'highfreq'","in","lnb","if","(","target_is_universal","and","(","not","is_universal_option",")",")",":","continue","if","(","info","[","'lnb'","]","[","'pol'","]",".","lower","(",")","==","\"dual\"","and","# user has dual-pol LNB","(","info","[","'sat'","]","[","'pol'","]","==","\"H\"","or","# and satellite requires H pol","(","'v1_pointed'","in","info","[","'lnb'","]","and","info","[","'lnb'","]","[","'v1_pointed'","]","and","info","[","'lnb'","]","[","'v1_psu_voltage'","]",">=","16","# or LNB already operates with H pol",")",")","and","\"rangeswitch\"","not","in","lnb",")",":","# but LNB candidate is single-pol","continue","# not a validate candidate, skip","if","(","target_is_universal",")",":","if","(","is_universal_option","and","lnb","[","'lowfreq'","]","==","target_lo_freq","[","0","]","and","lnb","[","'highfreq'","]","==","target_lo_freq","[","1","]",")",":","options",".","append","(","lnb",")","else",":","if","(","lnb","[","'lowfreq'","]","==","target_lo_freq","[","0","]",")",":","options",".","append","(","lnb",")","assert","(","len","(","options",")",">","0",")",",","\"LNB doesn't match a valid option\"","logger",".","debug","(","\"Matching LNB options: {}\"",".","format","(","pformat","(","options",")",")",")","return","options","[","0","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L17-L64"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_find_adapter","parameters":"(list_only=False, target_model=None)","argument_list":"","return_statement":"return chosen_adapter[\"adapter\"], chosen_adapter[\"frontend\"]","docstring":"Find the DVB adapter\n\n Returns:\n Tuple with (adapter index, frontend index)","docstring_summary":"Find the DVB adapter","docstring_tokens":["Find","the","DVB","adapter"],"function":"def _find_adapter(list_only=False, target_model=None):\n \"\"\"Find the DVB adapter\n\n Returns:\n Tuple with (adapter index, frontend index)\n\n \"\"\"\n if (target_model is None):\n util.print_header(\"Find DVB Adapter\")\n\n # Search a range of adapters. There is no command to list all adapters, so\n # we try to list each one individually using `dvbnet -a adapter_no -l`.\n adapters = list()\n for a in range(0, 10):\n cmd = [\"dvbnet\", \"-a\", str(a), \"-l\"]\n logger.debug(\"> \" + \" \".join(cmd))\n\n with open(os.devnull, 'w') as devnull:\n res = subprocess.call(cmd, stdout=devnull, stderr=devnull)\n if (res == 0):\n # Try a few frontends too\n for f in range(0, 2):\n try:\n output = subprocess.check_output(\n [\"dvb-fe-tool\", \"-a\",\n str(a), \"-f\",\n str(f)])\n line = output.splitlines()[0].decode().split()\n adapter = {\n \"adapter\":\n str(a),\n \"frontend\":\n line[5].replace(\")\", \"\").split(\"frontend\")[-1],\n \"vendor\":\n line[1],\n \"model\":\n \" \".join(line[2:4]),\n \"support\":\n line[4]\n }\n adapters.append(adapter)\n logger.debug(pformat(adapter))\n except subprocess.CalledProcessError:\n pass\n\n # If nothing was obtained using dvbnet, try to inspect dmesg logs\n if (len(adapters) == 0):\n ps = subprocess.Popen(\"dmesg\", stdout=subprocess.PIPE)\n try:\n output = subprocess.check_output([\"grep\", \"frontend\"],\n stdin=ps.stdout,\n stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError as grepexc:\n if (grepexc.returncode == 1):\n output = \"\"\n pass\n ps.wait()\n\n lines = output.splitlines()\n adapter_set = set() # use set to filter unique values\n adapters = list()\n for line in lines:\n linesplit = line.decode().split()\n if (\"adapter\" not in linesplit):\n continue\n i_adapter = linesplit.index('adapter')\n i_frontend = linesplit.index('frontend')\n device = linesplit[i_frontend + 2:]\n adapter = {\n \"adapter\": linesplit[i_adapter + 1],\n \"frontend\": linesplit[i_frontend + 1],\n \"vendor\": device[0][1:],\n \"model\": \" \".join(device[1:-1]),\n \"support\": device[-1][:-4].replace('(', '').replace(')', '')\n }\n\n # Maybe the device on dmesg does not exist anymore. Check!\n try:\n cmd = [\"dvbnet\", \"-a\", adapter['adapter'], \"-l\"]\n logger.debug(\"> \" + \" \".join(cmd))\n res = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)\n except subprocess.CalledProcessError:\n continue\n\n # If it exists, add to set of candidate adapters\n adapter_set.add(json.dumps(adapter))\n\n # Process unique adapter logs\n for adapter in adapter_set:\n adapters.append(json.loads(adapter))\n logger.debug(pformat(json.loads(adapter)))\n\n dvb_s2_adapters = [a for a in adapters if (\"DVB-S\/S2\" in a[\"support\"])]\n logger.debug(dvb_s2_adapters)\n\n assert (len(dvb_s2_adapters) > 0), \"No DVB-S2 adapters found\"\n\n chosen_adapter = None\n if (target_model is not None):\n # Search without prompting\n for adapter in dvb_s2_adapters:\n if (adapter[\"model\"] == target_model):\n chosen_adapter = adapter\n break\n else:\n # Prompt the user\n for adapter in dvb_s2_adapters:\n print(\"Found DVB-S2 adapter: %s %s\" %\n (adapter[\"vendor\"], adapter[\"model\"]))\n\n if (not list_only):\n if (len(dvb_s2_adapters) == 1\n or util.ask_yes_or_no(\"Choose adapter?\")):\n chosen_adapter = adapter\n logger.debug(\"Chosen adapter:\")\n logger.debug(pformat(adapter))\n break\n\n if (list_only):\n return\n\n if (chosen_adapter is None):\n if (target_model is None):\n err_msg = \"Please choose a DVB-S2 adapter\"\n else:\n err_msg = \"Please choose a valid DVB-S2 adapter\"\n raise ValueError(err_msg)\n\n return chosen_adapter[\"adapter\"], chosen_adapter[\"frontend\"]","function_tokens":["def","_find_adapter","(","list_only","=","False",",","target_model","=","None",")",":","if","(","target_model","is","None",")",":","util",".","print_header","(","\"Find DVB Adapter\"",")","# Search a range of adapters. There is no command to list all adapters, so","# we try to list each one individually using `dvbnet -a adapter_no -l`.","adapters","=","list","(",")","for","a","in","range","(","0",",","10",")",":","cmd","=","[","\"dvbnet\"",",","\"-a\"",",","str","(","a",")",",","\"-l\"","]","logger",".","debug","(","\"> \"","+","\" \"",".","join","(","cmd",")",")","with","open","(","os",".","devnull",",","'w'",")","as","devnull",":","res","=","subprocess",".","call","(","cmd",",","stdout","=","devnull",",","stderr","=","devnull",")","if","(","res","==","0",")",":","# Try a few frontends too","for","f","in","range","(","0",",","2",")",":","try",":","output","=","subprocess",".","check_output","(","[","\"dvb-fe-tool\"",",","\"-a\"",",","str","(","a",")",",","\"-f\"",",","str","(","f",")","]",")","line","=","output",".","splitlines","(",")","[","0","]",".","decode","(",")",".","split","(",")","adapter","=","{","\"adapter\"",":","str","(","a",")",",","\"frontend\"",":","line","[","5","]",".","replace","(","\")\"",",","\"\"",")",".","split","(","\"frontend\"",")","[","-","1","]",",","\"vendor\"",":","line","[","1","]",",","\"model\"",":","\" \"",".","join","(","line","[","2",":","4","]",")",",","\"support\"",":","line","[","4","]","}","adapters",".","append","(","adapter",")","logger",".","debug","(","pformat","(","adapter",")",")","except","subprocess",".","CalledProcessError",":","pass","# If nothing was obtained using dvbnet, try to inspect dmesg logs","if","(","len","(","adapters",")","==","0",")",":","ps","=","subprocess",".","Popen","(","\"dmesg\"",",","stdout","=","subprocess",".","PIPE",")","try",":","output","=","subprocess",".","check_output","(","[","\"grep\"",",","\"frontend\"","]",",","stdin","=","ps",".","stdout",",","stderr","=","subprocess",".","STDOUT",")","except","subprocess",".","CalledProcessError","as","grepexc",":","if","(","grepexc",".","returncode","==","1",")",":","output","=","\"\"","pass","ps",".","wait","(",")","lines","=","output",".","splitlines","(",")","adapter_set","=","set","(",")","# use set to filter unique values","adapters","=","list","(",")","for","line","in","lines",":","linesplit","=","line",".","decode","(",")",".","split","(",")","if","(","\"adapter\"","not","in","linesplit",")",":","continue","i_adapter","=","linesplit",".","index","(","'adapter'",")","i_frontend","=","linesplit",".","index","(","'frontend'",")","device","=","linesplit","[","i_frontend","+","2",":","]","adapter","=","{","\"adapter\"",":","linesplit","[","i_adapter","+","1","]",",","\"frontend\"",":","linesplit","[","i_frontend","+","1","]",",","\"vendor\"",":","device","[","0","]","[","1",":","]",",","\"model\"",":","\" \"",".","join","(","device","[","1",":","-","1","]",")",",","\"support\"",":","device","[","-","1","]","[",":","-","4","]",".","replace","(","'('",",","''",")",".","replace","(","')'",",","''",")","}","# Maybe the device on dmesg does not exist anymore. Check!","try",":","cmd","=","[","\"dvbnet\"",",","\"-a\"",",","adapter","[","'adapter'","]",",","\"-l\"","]","logger",".","debug","(","\"> \"","+","\" \"",".","join","(","cmd",")",")","res","=","subprocess",".","check_output","(","cmd",",","stderr","=","subprocess",".","DEVNULL",")","except","subprocess",".","CalledProcessError",":","continue","# If it exists, add to set of candidate adapters","adapter_set",".","add","(","json",".","dumps","(","adapter",")",")","# Process unique adapter logs","for","adapter","in","adapter_set",":","adapters",".","append","(","json",".","loads","(","adapter",")",")","logger",".","debug","(","pformat","(","json",".","loads","(","adapter",")",")",")","dvb_s2_adapters","=","[","a","for","a","in","adapters","if","(","\"DVB-S\/S2\"","in","a","[","\"support\"","]",")","]","logger",".","debug","(","dvb_s2_adapters",")","assert","(","len","(","dvb_s2_adapters",")",">","0",")",",","\"No DVB-S2 adapters found\"","chosen_adapter","=","None","if","(","target_model","is","not","None",")",":","# Search without prompting","for","adapter","in","dvb_s2_adapters",":","if","(","adapter","[","\"model\"","]","==","target_model",")",":","chosen_adapter","=","adapter","break","else",":","# Prompt the user","for","adapter","in","dvb_s2_adapters",":","print","(","\"Found DVB-S2 adapter: %s %s\"","%","(","adapter","[","\"vendor\"","]",",","adapter","[","\"model\"","]",")",")","if","(","not","list_only",")",":","if","(","len","(","dvb_s2_adapters",")","==","1","or","util",".","ask_yes_or_no","(","\"Choose adapter?\"",")",")",":","chosen_adapter","=","adapter","logger",".","debug","(","\"Chosen adapter:\"",")","logger",".","debug","(","pformat","(","adapter",")",")","break","if","(","list_only",")",":","return","if","(","chosen_adapter","is","None",")",":","if","(","target_model","is","None",")",":","err_msg","=","\"Please choose a DVB-S2 adapter\"","else",":","err_msg","=","\"Please choose a valid DVB-S2 adapter\"","raise","ValueError","(","err_msg",")","return","chosen_adapter","[","\"adapter\"","]",",","chosen_adapter","[","\"frontend\"","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L67-L195"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_dvbnet_single","parameters":"(adapter, ifname, pid, ule, existing_dvbnet_interfaces)","argument_list":"","return_statement":"","docstring":"Start DVB network interface\n\n Args:\n adapter : DVB adapter index\n ifname : DVB network interface name\n pid : PID to listen to\n ule : Whether to use ULE framing\n existing_dvbnet_interfaces : List of dvbnet interfaces already\n configured for the adapter","docstring_summary":"Start DVB network interface","docstring_tokens":["Start","DVB","network","interface"],"function":"def _dvbnet_single(adapter, ifname, pid, ule, existing_dvbnet_interfaces):\n \"\"\"Start DVB network interface\n\n Args:\n adapter : DVB adapter index\n ifname : DVB network interface name\n pid : PID to listen to\n ule : Whether to use ULE framing\n existing_dvbnet_interfaces : List of dvbnet interfaces already\n configured for the adapter\n\n \"\"\"\n\n assert (pid >= 32 and pid <= 8190), \"PID not insider range 32 to 8190\"\n\n if (ule):\n encapsulation = 'ULE'\n else:\n encapsulation = 'MPE'\n\n # Check if the interface already exists\n res = subprocess.call([\"ip\", \"addr\", \"show\", \"dev\", ifname],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL)\n os_interface_exists = (res == 0)\n matching_dvbnet_if = None\n\n # When the network interface exists in the OS, we also need to check if the\n # matching dvbnet device is configured according to what we want now\n if (os_interface_exists):\n print(\"Network interface %s already exists\" % (ifname))\n\n for interface in existing_dvbnet_interfaces:\n if (interface['name'] == ifname):\n matching_dvbnet_if = interface\n break\n\n # Our indication that interface exists comes from \"ip addr show\n # dev\". However, it is possible that dvbnet does not have any interface\n # associated to an adapter, so check if we found anything:\n cfg_interface = False\n if (len(existing_dvbnet_interfaces) > 0\n and matching_dvbnet_if is not None):\n # Compare to desired configurations\n if (matching_dvbnet_if['pid'] != pid\n or matching_dvbnet_if['encapsulation'] != encapsulation):\n cfg_interface = True\n\n if (matching_dvbnet_if['pid'] != pid):\n print(\"Current PID is %d. Set it to %d\" %\n (matching_dvbnet_if['pid'], pid))\n\n if (matching_dvbnet_if['encapsulation'] != encapsulation):\n print(\"Current encapsulation is %s. Set it to %s\" %\n (matching_dvbnet_if['encapsulation'], encapsulation))\n else:\n cfg_interface = True\n\n # Create interface in case it doesn't exist or needs to be re-created\n if (cfg_interface):\n # If interface exists, but must be re-created, remove the existing one\n # first\n if (os_interface_exists):\n _rm_dvbnet_interface(adapter, ifname, verbose=False)\n\n ule_arg = \"-U\" if ule else \"\"\n\n if (runner.dry):\n print(\"Create interface {}:\".format(ifname))\n\n runner.run([\"dvbnet\", \"-a\", adapter, \"-p\",\n str(pid), ule_arg],\n root=True)\n else:\n print(\"Network interface %s already configured correctly\" % (ifname))","function_tokens":["def","_dvbnet_single","(","adapter",",","ifname",",","pid",",","ule",",","existing_dvbnet_interfaces",")",":","assert","(","pid",">=","32","and","pid","<=","8190",")",",","\"PID not insider range 32 to 8190\"","if","(","ule",")",":","encapsulation","=","'ULE'","else",":","encapsulation","=","'MPE'","# Check if the interface already exists","res","=","subprocess",".","call","(","[","\"ip\"",",","\"addr\"",",","\"show\"",",","\"dev\"",",","ifname","]",",","stdout","=","subprocess",".","DEVNULL",",","stderr","=","subprocess",".","DEVNULL",")","os_interface_exists","=","(","res","==","0",")","matching_dvbnet_if","=","None","# When the network interface exists in the OS, we also need to check if the","# matching dvbnet device is configured according to what we want now","if","(","os_interface_exists",")",":","print","(","\"Network interface %s already exists\"","%","(","ifname",")",")","for","interface","in","existing_dvbnet_interfaces",":","if","(","interface","[","'name'","]","==","ifname",")",":","matching_dvbnet_if","=","interface","break","# Our indication that interface exists comes from \"ip addr show","# dev\". However, it is possible that dvbnet does not have any interface","# associated to an adapter, so check if we found anything:","cfg_interface","=","False","if","(","len","(","existing_dvbnet_interfaces",")",">","0","and","matching_dvbnet_if","is","not","None",")",":","# Compare to desired configurations","if","(","matching_dvbnet_if","[","'pid'","]","!=","pid","or","matching_dvbnet_if","[","'encapsulation'","]","!=","encapsulation",")",":","cfg_interface","=","True","if","(","matching_dvbnet_if","[","'pid'","]","!=","pid",")",":","print","(","\"Current PID is %d. Set it to %d\"","%","(","matching_dvbnet_if","[","'pid'","]",",","pid",")",")","if","(","matching_dvbnet_if","[","'encapsulation'","]","!=","encapsulation",")",":","print","(","\"Current encapsulation is %s. Set it to %s\"","%","(","matching_dvbnet_if","[","'encapsulation'","]",",","encapsulation",")",")","else",":","cfg_interface","=","True","# Create interface in case it doesn't exist or needs to be re-created","if","(","cfg_interface",")",":","# If interface exists, but must be re-created, remove the existing one","# first","if","(","os_interface_exists",")",":","_rm_dvbnet_interface","(","adapter",",","ifname",",","verbose","=","False",")","ule_arg","=","\"-U\"","if","ule","else","\"\"","if","(","runner",".","dry",")",":","print","(","\"Create interface {}:\"",".","format","(","ifname",")",")","runner",".","run","(","[","\"dvbnet\"",",","\"-a\"",",","adapter",",","\"-p\"",",","str","(","pid",")",",","ule_arg","]",",","root","=","True",")","else",":","print","(","\"Network interface %s already configured correctly\"","%","(","ifname",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L198-L272"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_dvbnet","parameters":"(adapter, ifnames, pids, ule=False)","argument_list":"","return_statement":"","docstring":"Start DVB network interfaces of a DVB adapter\n\n An adapter can have multiple dvbnet interfaces, one for each PID.\n\n Args:\n adapter : DVB adapter index\n ifnames : list of DVB network interface names\n pids : List of PIDs to listen to on each interface\n ule : Whether to use ULE framing","docstring_summary":"Start DVB network interfaces of a DVB adapter","docstring_tokens":["Start","DVB","network","interfaces","of","a","DVB","adapter"],"function":"def _dvbnet(adapter, ifnames, pids, ule=False):\n \"\"\"Start DVB network interfaces of a DVB adapter\n\n An adapter can have multiple dvbnet interfaces, one for each PID.\n\n Args:\n adapter : DVB adapter index\n ifnames : list of DVB network interface names\n pids : List of PIDs to listen to on each interface\n ule : Whether to use ULE framing\n\n \"\"\"\n assert (isinstance(ifnames, list))\n assert (isinstance(pids, list))\n assert(len(ifnames) == len(pids)), \\\n \"Interface names and PID number must be vectors of the same length\"\n\n # Find the dvbnet interfaces that already exist for the chosen adapter\n existing_dvbnet_iif = _find_dvbnet_interfaces(adapter)\n\n util.print_header(\"Network Interface\")\n\n for ifname, pid in zip(ifnames, pids):\n _dvbnet_single(adapter, ifname, pid, ule, existing_dvbnet_iif)","function_tokens":["def","_dvbnet","(","adapter",",","ifnames",",","pids",",","ule","=","False",")",":","assert","(","isinstance","(","ifnames",",","list",")",")","assert","(","isinstance","(","pids",",","list",")",")","assert","(","len","(","ifnames",")","==","len","(","pids",")",")",",","\"Interface names and PID number must be vectors of the same length\"","# Find the dvbnet interfaces that already exist for the chosen adapter","existing_dvbnet_iif","=","_find_dvbnet_interfaces","(","adapter",")","util",".","print_header","(","\"Network Interface\"",")","for","ifname",",","pid","in","zip","(","ifnames",",","pids",")",":","_dvbnet_single","(","adapter",",","ifname",",","pid",",","ule",",","existing_dvbnet_iif",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L275-L298"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_find_dvbnet_interfaces","parameters":"(adapter)","argument_list":"","return_statement":"return interfaces","docstring":"Find dvbnet interface(s) of a DVB adapter\n\n An adapter can have multiple dvbnet interfaces, one for each PID.\n\n Args:\n adapter: Corresponding DVB adapter\n\n Returns:\n interfaces : List of dvbnet interfaces","docstring_summary":"Find dvbnet interface(s) of a DVB adapter","docstring_tokens":["Find","dvbnet","interface","(","s",")","of","a","DVB","adapter"],"function":"def _find_dvbnet_interfaces(adapter):\n \"\"\"Find dvbnet interface(s) of a DVB adapter\n\n An adapter can have multiple dvbnet interfaces, one for each PID.\n\n Args:\n adapter: Corresponding DVB adapter\n\n Returns:\n interfaces : List of dvbnet interfaces\n\n \"\"\"\n\n util.print_header(\"Find dvbnet interface(s)\")\n cmd = [\"dvbnet\", \"-a\", adapter, \"-l\"]\n logger.debug(\"> \" + \" \".join(cmd))\n res = subprocess.check_output(cmd)\n\n interfaces = list()\n for line in res.splitlines():\n if (\"Found device\" in line.decode()):\n line_split = line.decode().split()\n interface = {\n 'dev': line_split[2][:-1],\n 'name': line_split[4][:-1],\n 'pid': int(line_split[8][:-1]),\n 'encapsulation': line_split[10]\n }\n logger.debug(pformat(interface))\n interfaces.append(interface)\n\n if (len(interfaces) == 0):\n print(\"Could not find any dvbnet interface\")\n\n return interfaces","function_tokens":["def","_find_dvbnet_interfaces","(","adapter",")",":","util",".","print_header","(","\"Find dvbnet interface(s)\"",")","cmd","=","[","\"dvbnet\"",",","\"-a\"",",","adapter",",","\"-l\"","]","logger",".","debug","(","\"> \"","+","\" \"",".","join","(","cmd",")",")","res","=","subprocess",".","check_output","(","cmd",")","interfaces","=","list","(",")","for","line","in","res",".","splitlines","(",")",":","if","(","\"Found device\"","in","line",".","decode","(",")",")",":","line_split","=","line",".","decode","(",")",".","split","(",")","interface","=","{","'dev'",":","line_split","[","2","]","[",":","-","1","]",",","'name'",":","line_split","[","4","]","[",":","-","1","]",",","'pid'",":","int","(","line_split","[","8","]","[",":","-","1","]",")",",","'encapsulation'",":","line_split","[","10","]","}","logger",".","debug","(","pformat","(","interface",")",")","interfaces",".","append","(","interface",")","if","(","len","(","interfaces",")","==","0",")",":","print","(","\"Could not find any dvbnet interface\"",")","return","interfaces"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L301-L335"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_rm_dvbnet_interface","parameters":"(adapter, ifname, verbose=True)","argument_list":"","return_statement":"","docstring":"Remove DVB net interface\n\n Args:\n adapter : Corresponding DVB adapter\n interface : dvbnet interface number\n verbose : Controls verbosity","docstring_summary":"Remove DVB net interface","docstring_tokens":["Remove","DVB","net","interface"],"function":"def _rm_dvbnet_interface(adapter, ifname, verbose=True):\n \"\"\"Remove DVB net interface\n\n Args:\n adapter : Corresponding DVB adapter\n interface : dvbnet interface number\n verbose : Controls verbosity\n \"\"\"\n\n if (verbose):\n util.print_header(\"Remove dvbnet interface\")\n\n runner.run([\"ip\", \"link\", \"set\", ifname, \"down\"], root=True)\n\n if_number = ifname.split(\"_\")[-1]\n runner.run([\"dvbnet\", \"-a\", adapter, \"-d\", if_number], root=True)\n\n # Remove also the static IP address configuration\n ip.rm_ip(ifname, runner.dry)","function_tokens":["def","_rm_dvbnet_interface","(","adapter",",","ifname",",","verbose","=","True",")",":","if","(","verbose",")",":","util",".","print_header","(","\"Remove dvbnet interface\"",")","runner",".","run","(","[","\"ip\"",",","\"link\"",",","\"set\"",",","ifname",",","\"down\"","]",",","root","=","True",")","if_number","=","ifname",".","split","(","\"_\"",")","[","-","1","]","runner",".","run","(","[","\"dvbnet\"",",","\"-a\"",",","adapter",",","\"-d\"",",","if_number","]",",","root","=","True",")","# Remove also the static IP address configuration","ip",".","rm_ip","(","ifname",",","runner",".","dry",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L338-L356"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"zap","parameters":"(adapter,\n frontend,\n ch_conf_file,\n user_info,\n lnb=\"UNIVERSAL\",\n output=None,\n timeout=None,\n monitor=False)","argument_list":"","return_statement":"return ps","docstring":"Run zapper\n\n Args:\n adapter : DVB adapter index\n frontend : frontend\n ch_conf_file : Path to channel configurations file\n user_info : Dictionary with user configurations\n lnb : LNB type\n output : Output filename (when recording)\n timeout : Run the zap for this specified duration\n monitor : Monitor mode. Monitors DVB traffic stats (throughput and\n packets per second), but does not deliver data upstream.\n\n Returns:\n Subprocess object","docstring_summary":"Run zapper","docstring_tokens":["Run","zapper"],"function":"def zap(adapter,\n frontend,\n ch_conf_file,\n user_info,\n lnb=\"UNIVERSAL\",\n output=None,\n timeout=None,\n monitor=False):\n \"\"\"Run zapper\n\n Args:\n adapter : DVB adapter index\n frontend : frontend\n ch_conf_file : Path to channel configurations file\n user_info : Dictionary with user configurations\n lnb : LNB type\n output : Output filename (when recording)\n timeout : Run the zap for this specified duration\n monitor : Monitor mode. Monitors DVB traffic stats (throughput and\n packets per second), but does not deliver data upstream.\n\n Returns:\n Subprocess object\n\n \"\"\"\n\n util.print_header(\"Tuning the DVB-S2 Receiver\")\n\n # LNB name to use when calling dvbv5-zap\n if (lnb is None):\n # Find suitable LNB within v4l-utils preset LNBs\n lnb = _find_v4l_lnb(user_info)['alias']\n\n print(\"Running dvbv5-zap\")\n print(\" - Config: {}\".format(ch_conf_file))\n print(\" - Adapter: {}\".format(adapter))\n print(\" - Frontend: {}\".format(frontend))\n print(\" - LNB: {}\".format(lnb))\n\n cmd = [\n \"dvbv5-zap\", \"-c\", ch_conf_file, \"-a\",\n str(adapter), \"-f\",\n str(frontend), \"-l\", lnb, \"-v\"\n ]\n\n rec_mode = output is not None\n if (rec_mode):\n cmd = cmd + [\"-o\", output]\n\n if (os.path.exists(output)):\n print(\"File %s already exists\" % (output))\n\n # The recording is such that MPEG TS packets are overwritten one by\n # one. For instance, if previous ts file had 1000 MPEG TS packets,\n # when overwriting, the tool would overwrite each packet\n # individually. So if it was stopped for instance after the first\n # 10 MPEG TS packets, only the first 10 would be overwritten, the\n # remaining MPEG TS packets would remain in the ts file.\n #\n # The other option is to remove the ts file completely and start a\n # new one. This way, all previous ts packets are guaranteed to be\n # erased.\n raw_resp = input(\n \"Remove and start new (R) or Overwrite (O)? [R\/O] \")\n response = raw_resp.lower()\n\n if (response == \"r\"):\n os.remove(output)\n elif (response != \"o\"):\n raise ValueError(\"Unknown response\")\n\n if (timeout is not None):\n cmd = cmd + [\"-t\", timeout]\n\n if (monitor):\n assert(output is None), \\\n \"Monitor mode does not work if recording (i.e. w\/ -r flag)\"\n cmd.append(\"-m\")\n\n cmd.append(\"blocksat-ch\")\n\n logger.debug(\"> \" + \" \".join(cmd))\n\n # Make sure the locale of dvbv5-zap is set to English. Otherwise, the\n # parser of \"_parse_log\" would not work.\n new_env = dict(os.environ)\n new_env['LC_ALL'] = 'C'\n\n if (monitor or rec_mode):\n ps = subprocess.Popen(cmd, env=new_env)\n else:\n ps = subprocess.Popen(cmd,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.PIPE,\n env=new_env,\n universal_newlines=True)\n return ps","function_tokens":["def","zap","(","adapter",",","frontend",",","ch_conf_file",",","user_info",",","lnb","=","\"UNIVERSAL\"",",","output","=","None",",","timeout","=","None",",","monitor","=","False",")",":","util",".","print_header","(","\"Tuning the DVB-S2 Receiver\"",")","# LNB name to use when calling dvbv5-zap","if","(","lnb","is","None",")",":","# Find suitable LNB within v4l-utils preset LNBs","lnb","=","_find_v4l_lnb","(","user_info",")","[","'alias'","]","print","(","\"Running dvbv5-zap\"",")","print","(","\" - Config: {}\"",".","format","(","ch_conf_file",")",")","print","(","\" - Adapter: {}\"",".","format","(","adapter",")",")","print","(","\" - Frontend: {}\"",".","format","(","frontend",")",")","print","(","\" - LNB: {}\"",".","format","(","lnb",")",")","cmd","=","[","\"dvbv5-zap\"",",","\"-c\"",",","ch_conf_file",",","\"-a\"",",","str","(","adapter",")",",","\"-f\"",",","str","(","frontend",")",",","\"-l\"",",","lnb",",","\"-v\"","]","rec_mode","=","output","is","not","None","if","(","rec_mode",")",":","cmd","=","cmd","+","[","\"-o\"",",","output","]","if","(","os",".","path",".","exists","(","output",")",")",":","print","(","\"File %s already exists\"","%","(","output",")",")","# The recording is such that MPEG TS packets are overwritten one by","# one. For instance, if previous ts file had 1000 MPEG TS packets,","# when overwriting, the tool would overwrite each packet","# individually. So if it was stopped for instance after the first","# 10 MPEG TS packets, only the first 10 would be overwritten, the","# remaining MPEG TS packets would remain in the ts file.","#","# The other option is to remove the ts file completely and start a","# new one. This way, all previous ts packets are guaranteed to be","# erased.","raw_resp","=","input","(","\"Remove and start new (R) or Overwrite (O)? [R\/O] \"",")","response","=","raw_resp",".","lower","(",")","if","(","response","==","\"r\"",")",":","os",".","remove","(","output",")","elif","(","response","!=","\"o\"",")",":","raise","ValueError","(","\"Unknown response\"",")","if","(","timeout","is","not","None",")",":","cmd","=","cmd","+","[","\"-t\"",",","timeout","]","if","(","monitor",")",":","assert","(","output","is","None",")",",","\"Monitor mode does not work if recording (i.e. w\/ -r flag)\"","cmd",".","append","(","\"-m\"",")","cmd",".","append","(","\"blocksat-ch\"",")","logger",".","debug","(","\"> \"","+","\" \"",".","join","(","cmd",")",")","# Make sure the locale of dvbv5-zap is set to English. Otherwise, the","# parser of \"_parse_log\" would not work.","new_env","=","dict","(","os",".","environ",")","new_env","[","'LC_ALL'","]","=","'C'","if","(","monitor","or","rec_mode",")",":","ps","=","subprocess",".","Popen","(","cmd",",","env","=","new_env",")","else",":","ps","=","subprocess",".","Popen","(","cmd",",","stdout","=","subprocess",".","DEVNULL",",","stderr","=","subprocess",".","PIPE",",","env","=","new_env",",","universal_newlines","=","True",")","return","ps"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L359-L455"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Subparser for usb command","docstring_summary":"Subparser for usb command","docstring_tokens":["Subparser","for","usb","command"],"function":"def subparser(subparsers):\n \"\"\"Subparser for usb command\"\"\"\n p = subparsers.add_parser('usb',\n description=\"USB DVB-S2 receiver manager\",\n help='Manage Linux USB DVB-S2 receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n # Common parameters\n p.add_argument('-a',\n '--adapter',\n default=None,\n help='DVB-S2 adapter number or model')\n\n p.add_argument('-f',\n '--frontend',\n default=None,\n help='DVB-S2 adapter\\'s frontend number')\n\n p.set_defaults(func=print_help)\n\n subsubparsers = p.add_subparsers(title='subcommands',\n help='Target sub-command')\n\n # Launch\n p1 = subsubparsers.add_parser(\n 'launch',\n description=\"Launch a USB DVB-S2 receiver\",\n help='Launch a Linux USB DVB-S2 receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n p1.add_argument(\n '-l',\n '--lnb',\n choices=defs.lnb_options,\n default=None,\n metavar='',\n help=\"LNB being used. If not specified, it will be defined \"\n \"automatically. Choose from the following LNBs supported \"\n \"by v4l-utils: \" + \", \".join(defs.lnb_options))\n\n p1.add_argument('-r',\n '--record-file',\n default=None,\n help='Record MPEG-TS traffic into a target file')\n\n p1.add_argument('-t',\n '--timeout',\n default=None,\n help='Stop zapping after a timeout in seconds - useful to \\\n control recording time')\n\n p1.add_argument('-m',\n '--monitor',\n default=False,\n action='store_true',\n help='Launch dvbv5-zap in monitor mode to debug MPEG TS '\n 'packet and bit rates')\n\n monitoring.add_to_parser(p1)\n\n p1.set_defaults(func=launch)\n\n # Initial configurations\n p2 = subsubparsers.add_parser(\n 'config',\n aliases=['cfg'],\n description='Initial configurations',\n help='Configure DVB-S2 interface(s) and\\\n the host',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p2.add_argument('-U',\n '--ule',\n default=False,\n action='store_true',\n help='Use ULE encapsulation instead of MPE')\n\n p2.add_argument('--skip-rp',\n default=False,\n action='store_true',\n help='Skip settting of reverse path filters')\n\n p2.add_argument('--skip-firewall',\n default=False,\n action='store_true',\n help='Skip configuration of firewall rules')\n\n p2.add_argument('--pid',\n default=defs.pids,\n type=int,\n nargs='+',\n help='List of PIDs to be listened to by dvbnet')\n\n p2.add_argument('-i',\n '--ip',\n default=None,\n nargs='+',\n help='IP address set for each DVB-S2 net \\\n interface with subnet mask in CIDR notation')\n\n p2.add_argument('-y',\n '--yes',\n default=False,\n action='store_true',\n help=\"Default to answering Yes to configuration prompts\")\n\n p2.add_argument(\"--dry-run\",\n action='store_true',\n default=False,\n help=\"Print all commands but do not execute them\")\n\n p2.set_defaults(func=usb_config)\n\n # Find adapter sub-command\n p3 = subsubparsers.add_parser(\n 'list',\n aliases=['ls'],\n description=\"List DVB-S2 adapters\",\n help='List DVB-S2 adapters',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p3.set_defaults(func=list_subcommand)\n\n # Remove adapter sub-command\n p4 = subsubparsers.add_parser(\n 'remove',\n aliases=['rm'],\n description=\"Remove DVB-S2 adapter\",\n help='Remove DVB-S2 adapter',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p4.add_argument('--all',\n default=False,\n action='store_true',\n help='Remove all dvbnet interfaces associated with the '\n 'adapter')\n p4.add_argument(\"--dry-run\",\n action='store_true',\n default=False,\n help=\"Print all commands but do not execute them\")\n p4.set_defaults(func=rm_subcommand)\n\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'usb'",",","description","=","\"USB DVB-S2 receiver manager\"",",","help","=","'Manage Linux USB DVB-S2 receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","# Common parameters","p",".","add_argument","(","'-a'",",","'--adapter'",",","default","=","None",",","help","=","'DVB-S2 adapter number or model'",")","p",".","add_argument","(","'-f'",",","'--frontend'",",","default","=","None",",","help","=","'DVB-S2 adapter\\'s frontend number'",")","p",".","set_defaults","(","func","=","print_help",")","subsubparsers","=","p",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",")","# Launch","p1","=","subsubparsers",".","add_parser","(","'launch'",",","description","=","\"Launch a USB DVB-S2 receiver\"",",","help","=","'Launch a Linux USB DVB-S2 receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p1",".","add_argument","(","'-l'",",","'--lnb'",",","choices","=","defs",".","lnb_options",",","default","=","None",",","metavar","=","''",",","help","=","\"LNB being used. If not specified, it will be defined \"","\"automatically. Choose from the following LNBs supported \"","\"by v4l-utils: \"","+","\", \"",".","join","(","defs",".","lnb_options",")",")","p1",".","add_argument","(","'-r'",",","'--record-file'",",","default","=","None",",","help","=","'Record MPEG-TS traffic into a target file'",")","p1",".","add_argument","(","'-t'",",","'--timeout'",",","default","=","None",",","help","=","'Stop zapping after a timeout in seconds - useful to \\\n control recording time'",")","p1",".","add_argument","(","'-m'",",","'--monitor'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Launch dvbv5-zap in monitor mode to debug MPEG TS '","'packet and bit rates'",")","monitoring",".","add_to_parser","(","p1",")","p1",".","set_defaults","(","func","=","launch",")","# Initial configurations","p2","=","subsubparsers",".","add_parser","(","'config'",",","aliases","=","[","'cfg'","]",",","description","=","'Initial configurations'",",","help","=","'Configure DVB-S2 interface(s) and\\\n the host'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p2",".","add_argument","(","'-U'",",","'--ule'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Use ULE encapsulation instead of MPE'",")","p2",".","add_argument","(","'--skip-rp'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Skip settting of reverse path filters'",")","p2",".","add_argument","(","'--skip-firewall'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Skip configuration of firewall rules'",")","p2",".","add_argument","(","'--pid'",",","default","=","defs",".","pids",",","type","=","int",",","nargs","=","'+'",",","help","=","'List of PIDs to be listened to by dvbnet'",")","p2",".","add_argument","(","'-i'",",","'--ip'",",","default","=","None",",","nargs","=","'+'",",","help","=","'IP address set for each DVB-S2 net \\\n interface with subnet mask in CIDR notation'",")","p2",".","add_argument","(","'-y'",",","'--yes'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Default to answering Yes to configuration prompts\"",")","p2",".","add_argument","(","\"--dry-run\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Print all commands but do not execute them\"",")","p2",".","set_defaults","(","func","=","usb_config",")","# Find adapter sub-command","p3","=","subsubparsers",".","add_parser","(","'list'",",","aliases","=","[","'ls'","]",",","description","=","\"List DVB-S2 adapters\"",",","help","=","'List DVB-S2 adapters'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p3",".","set_defaults","(","func","=","list_subcommand",")","# Remove adapter sub-command","p4","=","subsubparsers",".","add_parser","(","'remove'",",","aliases","=","[","'rm'","]",",","description","=","\"Remove DVB-S2 adapter\"",",","help","=","'Remove DVB-S2 adapter'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p4",".","add_argument","(","'--all'",",","default","=","False",",","action","=","'store_true'",",","help","=","'Remove all dvbnet interfaces associated with the '","'adapter'",")","p4",".","add_argument","(","\"--dry-run\"",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Print all commands but do not execute them\"",")","p4",".","set_defaults","(","func","=","rm_subcommand",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L458-L597"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"usb_config","parameters":"(args)","argument_list":"","return_statement":"return","docstring":"Config the DVB interface(s) and the host","docstring_summary":"Config the DVB interface(s) and the host","docstring_tokens":["Config","the","DVB","interface","(","s",")","and","the","host"],"function":"def usb_config(args):\n \"\"\"Config the DVB interface(s) and the host\"\"\"\n common_params = _common(args)\n if (common_params is None):\n return\n user_info, adapter, frontend = common_params\n\n # Check if dependencies other than dvbnet are installed\n apps = [\"ip\"]\n if not args.skip_firewall:\n apps.append(\"iptables\")\n if (not dependencies.check_apps(apps)):\n return\n\n # Configure the subprocess runner\n runner.set_dry(args.dry_run)\n\n if args.ip is None:\n ips = ip.compute_rx_ips(user_info['sat']['ip'], len(args.pid))\n else:\n ips = args.ip\n\n assert (all([\"\/\" in x\n for x in ips])), \"Please provide IPs in CIDR notation\"\n\n assert(len(args.pid) == len(ips)), \\\n \"Please define one IP address for each PID.\"\n\n # dvbnet interfaces of interest\n #\n # NOTE: there is one dvbnet interface per PID. Each interface will have a\n # different IP address.\n net_ifs = list()\n for i_device in range(0, len(args.pid)):\n # Define interface name that is going to be generated by dvbnet\n net_if = \"dvb\" + adapter + \"_\" + str(i_device)\n net_ifs.append(net_if)\n\n # Create the dvbnet interface(s)\n _dvbnet(adapter, net_ifs, args.pid, ule=args.ule)\n\n # Set RP filters\n if (not args.skip_rp):\n rp.set_filters(net_ifs, prompt=(not args.yes), dry=args.dry_run)\n\n # Set firewall rules\n if (not args.skip_firewall):\n firewall.configure(net_ifs,\n defs.src_ports,\n user_info['sat']['ip'],\n prompt=(not args.yes),\n dry=args.dry_run)\n\n # Set IP\n ip.set_ips(net_ifs, ips, dry=runner.dry)\n\n util.print_header(\"Next Step\")\n print(\"Run:\\n\\nblocksat-cli usb launch\\n\")\n\n return","function_tokens":["def","usb_config","(","args",")",":","common_params","=","_common","(","args",")","if","(","common_params","is","None",")",":","return","user_info",",","adapter",",","frontend","=","common_params","# Check if dependencies other than dvbnet are installed","apps","=","[","\"ip\"","]","if","not","args",".","skip_firewall",":","apps",".","append","(","\"iptables\"",")","if","(","not","dependencies",".","check_apps","(","apps",")",")",":","return","# Configure the subprocess runner","runner",".","set_dry","(","args",".","dry_run",")","if","args",".","ip","is","None",":","ips","=","ip",".","compute_rx_ips","(","user_info","[","'sat'","]","[","'ip'","]",",","len","(","args",".","pid",")",")","else",":","ips","=","args",".","ip","assert","(","all","(","[","\"\/\"","in","x","for","x","in","ips","]",")",")",",","\"Please provide IPs in CIDR notation\"","assert","(","len","(","args",".","pid",")","==","len","(","ips",")",")",",","\"Please define one IP address for each PID.\"","# dvbnet interfaces of interest","#","# NOTE: there is one dvbnet interface per PID. Each interface will have a","# different IP address.","net_ifs","=","list","(",")","for","i_device","in","range","(","0",",","len","(","args",".","pid",")",")",":","# Define interface name that is going to be generated by dvbnet","net_if","=","\"dvb\"","+","adapter","+","\"_\"","+","str","(","i_device",")","net_ifs",".","append","(","net_if",")","# Create the dvbnet interface(s)","_dvbnet","(","adapter",",","net_ifs",",","args",".","pid",",","ule","=","args",".","ule",")","# Set RP filters","if","(","not","args",".","skip_rp",")",":","rp",".","set_filters","(","net_ifs",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")","# Set firewall rules","if","(","not","args",".","skip_firewall",")",":","firewall",".","configure","(","net_ifs",",","defs",".","src_ports",",","user_info","[","'sat'","]","[","'ip'","]",",","prompt","=","(","not","args",".","yes",")",",","dry","=","args",".","dry_run",")","# Set IP","ip",".","set_ips","(","net_ifs",",","ips",",","dry","=","runner",".","dry",")","util",".","print_header","(","\"Next Step\"",")","print","(","\"Run:\\n\\nblocksat-cli usb launch\\n\"",")","return"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L635-L694"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"_parse_log","parameters":"(line)","argument_list":"","return_statement":"return d","docstring":"Parse logs from dvbv5-zap and convert to the monitoring format\n\n The monitoring format is the format accepted by the monitor.py module.","docstring_summary":"Parse logs from dvbv5-zap and convert to the monitoring format","docstring_tokens":["Parse","logs","from","dvbv5","-","zap","and","convert","to","the","monitoring","format"],"function":"def _parse_log(line):\n \"\"\"Parse logs from dvbv5-zap and convert to the monitoring format\n\n The monitoring format is the format accepted by the monitor.py module.\n\n \"\"\"\n if (line is None or line == \"\\n\"):\n return\n\n # Don't process the \"Layer A\" lines\n if (\"Layer\" in line):\n return\n\n # Only process lines containing \"Signal\"\n if (\"Signal\" not in line):\n return\n d = {}\n elements = line.split()\n n_elem = len(elements)\n d['lock'] = (\"Lock\" in line, None)\n for i, elem in enumerate(elements):\n # Each metric is printed as \"name=value\"\n if (elem[-1] == \"=\" and (i + 1) <= n_elem):\n key = elem[:-1]\n raw_value = elements[i + 1]\n\n # Convert key to the nomenclature adopted on monitor.py\n key = log_key_map[key]\n\n # Fix any scientific notation\n if (\"^\" in raw_value):\n raw_value = raw_value.replace(\"x10^\", \"e\")\n\n # Parse value and unit\n unit = None\n if (\"%\" in raw_value):\n unit = \"%\"\n val = float(raw_value[:-1].replace(\",\", \".\"))\n elif (raw_value[-2:] == \"dB\"):\n val = float(raw_value[:-2].replace(\",\", \".\"))\n unit = \"dB\"\n elif (raw_value[-3:] == \"dBm\"):\n val = float(raw_value[:-3].replace(\",\", \".\"))\n unit = \"dBm\"\n else:\n val = float(raw_value.replace(\",\", \".\"))\n\n d[key] = (val, unit)\n\n return d","function_tokens":["def","_parse_log","(","line",")",":","if","(","line","is","None","or","line","==","\"\\n\"",")",":","return","# Don't process the \"Layer A\" lines","if","(","\"Layer\"","in","line",")",":","return","# Only process lines containing \"Signal\"","if","(","\"Signal\"","not","in","line",")",":","return","d","=","{","}","elements","=","line",".","split","(",")","n_elem","=","len","(","elements",")","d","[","'lock'","]","=","(","\"Lock\"","in","line",",","None",")","for","i",",","elem","in","enumerate","(","elements",")",":","# Each metric is printed as \"name=value\"","if","(","elem","[","-","1","]","==","\"=\"","and","(","i","+","1",")","<=","n_elem",")",":","key","=","elem","[",":","-","1","]","raw_value","=","elements","[","i","+","1","]","# Convert key to the nomenclature adopted on monitor.py","key","=","log_key_map","[","key","]","# Fix any scientific notation","if","(","\"^\"","in","raw_value",")",":","raw_value","=","raw_value",".","replace","(","\"x10^\"",",","\"e\"",")","# Parse value and unit","unit","=","None","if","(","\"%\"","in","raw_value",")",":","unit","=","\"%\"","val","=","float","(","raw_value","[",":","-","1","]",".","replace","(","\",\"",",","\".\"",")",")","elif","(","raw_value","[","-","2",":","]","==","\"dB\"",")",":","val","=","float","(","raw_value","[",":","-","2","]",".","replace","(","\",\"",",","\".\"",")",")","unit","=","\"dB\"","elif","(","raw_value","[","-","3",":","]","==","\"dBm\"",")",":","val","=","float","(","raw_value","[",":","-","3","]",".","replace","(","\",\"",",","\".\"",")",")","unit","=","\"dBm\"","else",":","val","=","float","(","raw_value",".","replace","(","\",\"",",","\".\"",")",")","d","[","key","]","=","(","val",",","unit",")","return","d"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L705-L754"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"launch","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Launch the DVB interface from scratch\n\n Handles the launch subcommand","docstring_summary":"Launch the DVB interface from scratch","docstring_tokens":["Launch","the","DVB","interface","from","scratch"],"function":"def launch(args):\n \"\"\"Launch the DVB interface from scratch\n\n Handles the launch subcommand\n\n \"\"\"\n\n common_params = _common(args)\n if (common_params is None):\n return\n user_info, adapter, frontend = common_params\n\n # Check if all dependencies are installed\n if (not dependencies.check_apps([\"dvbv5-zap\"])):\n return\n\n # Check conflicting logging options\n if ((args.monitor or args.record_file)\n and (args.log_scrolling or args.log_file)):\n raise ValueError(\"Logging options are disabled when running with \"\n \"-m\/--monitor or -r\/--record-file\")\n\n # Log Monitoring\n monitor = monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=args.log_scrolling,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)\n\n # Channel configuration file\n chan_conf = user_info['setup']['channel']\n\n # Zap\n zap_ps = zap(adapter,\n frontend,\n chan_conf,\n user_info,\n lnb=args.lnb,\n output=args.record_file,\n timeout=args.timeout,\n monitor=args.monitor)\n\n # Handler for SIGINT\n def signal_handler(sig, frame):\n print('Stopping...')\n zap_ps.terminate()\n sys.exit(zap_ps.poll())\n\n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n\n util.print_header(\"Receiver Monitoring\")\n print()\n\n # Listen to dvbv5-zap indefinitely\n if (args.monitor or args.record_file):\n zap_ps.wait()\n else:\n while (zap_ps.poll() is None):\n line = zap_ps.stderr.readline()\n metrics = _parse_log(line)\n if (metrics is None):\n continue\n monitor.update(metrics)\n print()\n sys.exit(zap_ps.poll())","function_tokens":["def","launch","(","args",")",":","common_params","=","_common","(","args",")","if","(","common_params","is","None",")",":","return","user_info",",","adapter",",","frontend","=","common_params","# Check if all dependencies are installed","if","(","not","dependencies",".","check_apps","(","[","\"dvbv5-zap\"","]",")",")",":","return","# Check conflicting logging options","if","(","(","args",".","monitor","or","args",".","record_file",")","and","(","args",".","log_scrolling","or","args",".","log_file",")",")",":","raise","ValueError","(","\"Logging options are disabled when running with \"","\"-m\/--monitor or -r\/--record-file\"",")","# Log Monitoring","monitor","=","monitoring",".","Monitor","(","args",".","cfg_dir",",","logfile","=","args",".","log_file",",","scroll","=","args",".","log_scrolling",",","min_interval","=","args",".","log_interval",",","server","=","args",".","monitoring_server",",","port","=","args",".","monitoring_port",",","report","=","args",".","report",",","report_opts","=","monitoring",".","get_report_opts","(","args",")",",","utc","=","args",".","utc",")","# Channel configuration file","chan_conf","=","user_info","[","'setup'","]","[","'channel'","]","# Zap","zap_ps","=","zap","(","adapter",",","frontend",",","chan_conf",",","user_info",",","lnb","=","args",".","lnb",",","output","=","args",".","record_file",",","timeout","=","args",".","timeout",",","monitor","=","args",".","monitor",")","# Handler for SIGINT","def","signal_handler","(","sig",",","frame",")",":","print","(","'Stopping...'",")","zap_ps",".","terminate","(",")","sys",".","exit","(","zap_ps",".","poll","(",")",")","signal",".","signal","(","signal",".","SIGINT",",","signal_handler",")","signal",".","signal","(","signal",".","SIGTERM",",","signal_handler",")","util",".","print_header","(","\"Receiver Monitoring\"",")","print","(",")","# Listen to dvbv5-zap indefinitely","if","(","args",".","monitor","or","args",".","record_file",")",":","zap_ps",".","wait","(",")","else",":","while","(","zap_ps",".","poll","(",")","is","None",")",":","line","=","zap_ps",".","stderr",".","readline","(",")","metrics","=","_parse_log","(","line",")","if","(","metrics","is","None",")",":","continue","monitor",".","update","(","metrics",")","print","(",")","sys",".","exit","(","zap_ps",".","poll","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L757-L826"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"list_subcommand","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Call function that finds the DVB adapter\n\n Handles the find-adapter subcommand","docstring_summary":"Call function that finds the DVB adapter","docstring_tokens":["Call","function","that","finds","the","DVB","adapter"],"function":"def list_subcommand(args):\n \"\"\"Call function that finds the DVB adapter\n\n Handles the find-adapter subcommand\n\n \"\"\"\n if (not dependencies.check_apps([\"dvbnet\", \"dvb-fe-tool\"])):\n return\n\n _find_adapter(list_only=True)","function_tokens":["def","list_subcommand","(","args",")",":","if","(","not","dependencies",".","check_apps","(","[","\"dvbnet\"",",","\"dvb-fe-tool\"","]",")",")",":","return","_find_adapter","(","list_only","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L829-L838"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"rm_subcommand","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Remove DVB interface","docstring_summary":"Remove DVB interface","docstring_tokens":["Remove","DVB","interface"],"function":"def rm_subcommand(args):\n \"\"\"Remove DVB interface\n\n \"\"\"\n\n if (not dependencies.check_apps([\"dvbnet\", \"dvb-fe-tool\", \"ip\"])):\n return\n\n # Configure the subprocess runner\n runner.set_dry(args.dry_run)\n\n # Find adapter\n if (args.adapter is None):\n adapter, _ = _find_adapter()\n else:\n # If argument --adapter holds a digit-only string, assume it refers to\n # the adapter number. Otherwise, assume it refers to the target model.\n adapter = args.adapter if args.adapter.isdigit() else \\\n _find_adapter(target_model=args.adapter)[0]\n\n interfaces = _find_dvbnet_interfaces(adapter)\n chosen_devices = list()\n\n if (len(interfaces) > 1):\n if (args.all):\n for interface in interfaces:\n chosen_devices.append(interface['name'])\n else:\n print(\"Choose net device to remove:\")\n for i_dev, interface in enumerate(interfaces):\n print(\"[%2u] %s\" % (i_dev, interface['name']))\n print(\"[ *] all\")\n\n try:\n choice = input(\"Choose number: \")\n if (choice == \"*\"):\n i_chosen_devices = range(0, len(interfaces))\n else:\n i_chosen_devices = [int(choice)]\n except ValueError:\n raise ValueError(\n \"Please choose a number or \\\"*\\\" for all devices\")\n\n for i_chosen_dev in i_chosen_devices:\n if (i_chosen_dev > len(interfaces)):\n raise ValueError(\"Invalid number\")\n\n chosen_devices.append(interfaces[i_chosen_dev]['name'])\n\n elif (len(interfaces) == 0):\n print(\"No DVB network interfaces to remove\")\n return\n else:\n # There is a single interface\n chosen_devices.append(interfaces[0]['name'])\n\n for chosen_dev in chosen_devices:\n _rm_dvbnet_interface(adapter, chosen_dev)","function_tokens":["def","rm_subcommand","(","args",")",":","if","(","not","dependencies",".","check_apps","(","[","\"dvbnet\"",",","\"dvb-fe-tool\"",",","\"ip\"","]",")",")",":","return","# Configure the subprocess runner","runner",".","set_dry","(","args",".","dry_run",")","# Find adapter","if","(","args",".","adapter","is","None",")",":","adapter",",","_","=","_find_adapter","(",")","else",":","# If argument --adapter holds a digit-only string, assume it refers to","# the adapter number. Otherwise, assume it refers to the target model.","adapter","=","args",".","adapter","if","args",".","adapter",".","isdigit","(",")","else","_find_adapter","(","target_model","=","args",".","adapter",")","[","0","]","interfaces","=","_find_dvbnet_interfaces","(","adapter",")","chosen_devices","=","list","(",")","if","(","len","(","interfaces",")",">","1",")",":","if","(","args",".","all",")",":","for","interface","in","interfaces",":","chosen_devices",".","append","(","interface","[","'name'","]",")","else",":","print","(","\"Choose net device to remove:\"",")","for","i_dev",",","interface","in","enumerate","(","interfaces",")",":","print","(","\"[%2u] %s\"","%","(","i_dev",",","interface","[","'name'","]",")",")","print","(","\"[ *] all\"",")","try",":","choice","=","input","(","\"Choose number: \"",")","if","(","choice","==","\"*\"",")",":","i_chosen_devices","=","range","(","0",",","len","(","interfaces",")",")","else",":","i_chosen_devices","=","[","int","(","choice",")","]","except","ValueError",":","raise","ValueError","(","\"Please choose a number or \\\"*\\\" for all devices\"",")","for","i_chosen_dev","in","i_chosen_devices",":","if","(","i_chosen_dev",">","len","(","interfaces",")",")",":","raise","ValueError","(","\"Invalid number\"",")","chosen_devices",".","append","(","interfaces","[","i_chosen_dev","]","[","'name'","]",")","elif","(","len","(","interfaces",")","==","0",")",":","print","(","\"No DVB network interfaces to remove\"",")","return","else",":","# There is a single interface","chosen_devices",".","append","(","interfaces","[","0","]","[","'name'","]",")","for","chosen_dev","in","chosen_devices",":","_rm_dvbnet_interface","(","adapter",",","chosen_dev",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L841-L898"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/usb.py","language":"python","identifier":"print_help","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Re-create argparse's help menu for the usb command","docstring_summary":"Re-create argparse's help menu for the usb command","docstring_tokens":["Re","-","create","argparse","s","help","menu","for","the","usb","command"],"function":"def print_help(args):\n \"\"\"Re-create argparse's help menu for the usb command\"\"\"\n parser = ArgumentParser()\n subparsers = parser.add_subparsers(title='', help='')\n parser = subparser(subparsers)\n print(parser.format_help())","function_tokens":["def","print_help","(","args",")",":","parser","=","ArgumentParser","(",")","subparsers","=","parser",".","add_subparsers","(","title","=","''",",","help","=","''",")","parser","=","subparser","(","subparsers",")","print","(","parser",".","format_help","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/usb.py#L901-L906"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"_parse_modcod","parameters":"(modcod)","argument_list":"","return_statement":"","docstring":"Convert a given modcod into a dict with modulation type and code rate","docstring_summary":"Convert a given modcod into a dict with modulation type and code rate","docstring_tokens":["Convert","a","given","modcod","into","a","dict","with","modulation","type","and","code","rate"],"function":"def _parse_modcod(modcod):\n \"\"\"Convert a given modcod into a dict with modulation type and code rate\"\"\"\n mtypes = ['qpsk', '8psk', '16apsk', '32apsk']\n for mtype in mtypes:\n if mtype in modcod:\n fec = modcod.replace(mtype, '')\n return {'mtype': mtype, 'fec': fec}\n raise ValueError(\"Unsupported MODCOD {}\".format(modcod))","function_tokens":["def","_parse_modcod","(","modcod",")",":","mtypes","=","[","'qpsk'",",","'8psk'",",","'16apsk'",",","'32apsk'","]","for","mtype","in","mtypes",":","if","mtype","in","modcod",":","fec","=","modcod",".","replace","(","mtype",",","''",")","return","{","'mtype'",":","mtype",",","'fec'",":","fec","}","raise","ValueError","(","\"Unsupported MODCOD {}\"",".","format","(","modcod",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L597-L604"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"_get_monitor","parameters":"(args)","argument_list":"","return_statement":"return monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=scrolling,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)","docstring":"Create an object of the Monitor class\n\n Args:\n args : SDR parser arguments\n sat_name : Satellite name","docstring_summary":"Create an object of the Monitor class","docstring_tokens":["Create","an","object","of","the","Monitor","class"],"function":"def _get_monitor(args):\n \"\"\"Create an object of the Monitor class\n\n Args:\n args : SDR parser arguments\n sat_name : Satellite name\n\n \"\"\"\n # Force scrolling logs if tsp is configured to print to stdout or if\n # operating in debug mode\n scrolling = tsp.prints_to_stdout(args) or args.debug or args.log_scrolling\n\n return monitoring.Monitor(args.cfg_dir,\n logfile=args.log_file,\n scroll=scrolling,\n min_interval=args.log_interval,\n server=args.monitoring_server,\n port=args.monitoring_port,\n report=args.report,\n report_opts=monitoring.get_report_opts(args),\n utc=args.utc)","function_tokens":["def","_get_monitor","(","args",")",":","# Force scrolling logs if tsp is configured to print to stdout or if","# operating in debug mode","scrolling","=","tsp",".","prints_to_stdout","(","args",")","or","args",".","debug","or","args",".","log_scrolling","return","monitoring",".","Monitor","(","args",".","cfg_dir",",","logfile","=","args",".","log_file",",","scroll","=","scrolling",",","min_interval","=","args",".","log_interval",",","server","=","args",".","monitoring_server",",","port","=","args",".","monitoring_port",",","report","=","args",".","report",",","report_opts","=","monitoring",".","get_report_opts","(","args",")",",","utc","=","args",".","utc",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L607-L627"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"_monitoring_thread","parameters":"(sat_ip, handler)","argument_list":"","return_statement":"","docstring":"Loop used to monitor the DVB-S2 frontend on a thread","docstring_summary":"Loop used to monitor the DVB-S2 frontend on a thread","docstring_tokens":["Loop","used","to","monitor","the","DVB","-","S2","frontend","on","a","thread"],"function":"def _monitoring_thread(sat_ip, handler):\n \"\"\"Loop used to monitor the DVB-S2 frontend on a thread\"\"\"\n while (True):\n time.sleep(1)\n\n status = sat_ip.fe_stats()\n\n if (status is None):\n if (not handler.scroll):\n print()\n logger.warning(\"Failed to fetch the frontend status.\")\n continue\n\n handler.update(status)","function_tokens":["def","_monitoring_thread","(","sat_ip",",","handler",")",":","while","(","True",")",":","time",".","sleep","(","1",")","status","=","sat_ip",".","fe_stats","(",")","if","(","status","is","None",")",":","if","(","not","handler",".","scroll",")",":","print","(",")","logger",".","warning","(","\"Failed to fetch the frontend status.\"",")","continue","handler",".","update","(","status",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L630-L643"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Parser for sdr command","docstring_summary":"Parser for sdr command","docstring_tokens":["Parser","for","sdr","command"],"function":"def subparser(subparsers):\n \"\"\"Parser for sdr command\"\"\"\n p = subparsers.add_parser('sat-ip',\n description=\"Launch a Sat-IP receiver\",\n help='Launch a Sat-IP receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p.add_argument('-a', '--addr', help='Sat-IP antenna IP address')\n p.add_argument('-m',\n '--modcod',\n choices=defs.modcods.keys(),\n default='qpsk3\/5',\n metavar='',\n help=\"DVB-S2 modulation and coding (MODCOD) scheme. \"\n \"Choose from: \" + \", \".join(defs.modcods.keys()))\n p.add_argument('-u',\n '--username',\n default=DEFAULT_USERNAME,\n help='Sat-IP client username')\n p.add_argument('-p',\n '--password',\n default=DEFAULT_PASSWORD,\n help='Sat-IP client password')\n p.add_argument('--ssdp-src-port',\n type=int,\n help=\"Source port set on SSDP packets used to discover the \"\n \"Sat-IP server(s) in the network\")\n p.add_argument(\n '--ssdp-net-if',\n help=\"Network interface over which to send SSDP packets to discover \"\n \"the Sat-IP server(s) in the network\")\n p.add_argument('--no-fe-monitoring',\n default=True,\n action='store_false',\n dest='fe_monitoring',\n help=\"Do not monitor the Sat-IP server's physical frontend \"\n \"(DVB-S2 demodulator and tuner). Use this option when the \"\n \"server does not provide a login page or to avoid \"\n \"authentication conflicts between concurrent clients.\")\n p.add_argument(\n '--ignore-http-errors',\n default=False,\n action='store_true',\n help=\"Immediately retry the connection if an HTTP error occurs while \"\n \"reading the MPEG transport stream from the Sat-IP server\")\n tsp.add_to_parser(p)\n monitoring.add_to_parser(p)\n p.set_defaults(func=launch)\n return p","function_tokens":["def","subparser","(","subparsers",")",":","p","=","subparsers",".","add_parser","(","'sat-ip'",",","description","=","\"Launch a Sat-IP receiver\"",",","help","=","'Launch a Sat-IP receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p",".","add_argument","(","'-a'",",","'--addr'",",","help","=","'Sat-IP antenna IP address'",")","p",".","add_argument","(","'-m'",",","'--modcod'",",","choices","=","defs",".","modcods",".","keys","(",")",",","default","=","'qpsk3\/5'",",","metavar","=","''",",","help","=","\"DVB-S2 modulation and coding (MODCOD) scheme. \"","\"Choose from: \"","+","\", \"",".","join","(","defs",".","modcods",".","keys","(",")",")",")","p",".","add_argument","(","'-u'",",","'--username'",",","default","=","DEFAULT_USERNAME",",","help","=","'Sat-IP client username'",")","p",".","add_argument","(","'-p'",",","'--password'",",","default","=","DEFAULT_PASSWORD",",","help","=","'Sat-IP client password'",")","p",".","add_argument","(","'--ssdp-src-port'",",","type","=","int",",","help","=","\"Source port set on SSDP packets used to discover the \"","\"Sat-IP server(s) in the network\"",")","p",".","add_argument","(","'--ssdp-net-if'",",","help","=","\"Network interface over which to send SSDP packets to discover \"","\"the Sat-IP server(s) in the network\"",")","p",".","add_argument","(","'--no-fe-monitoring'",",","default","=","True",",","action","=","'store_false'",",","dest","=","'fe_monitoring'",",","help","=","\"Do not monitor the Sat-IP server's physical frontend \"","\"(DVB-S2 demodulator and tuner). Use this option when the \"","\"server does not provide a login page or to avoid \"","\"authentication conflicts between concurrent clients.\"",")","p",".","add_argument","(","'--ignore-http-errors'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Immediately retry the connection if an HTTP error occurs while \"","\"reading the MPEG transport stream from the Sat-IP server\"",")","tsp",".","add_to_parser","(","p",")","monitoring",".","add_to_parser","(","p",")","p",".","set_defaults","(","func","=","launch",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L646-L693"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.__init__","parameters":"(self, ip_addr=None, port=8000)","argument_list":"","return_statement":"","docstring":"Constructor\n\n Args:\n ip_addr : IP address of the Sat-IP server.\n port : Sat-IP server's HTTP port.","docstring_summary":"Constructor","docstring_tokens":["Constructor"],"function":"def __init__(self, ip_addr=None, port=8000):\n \"\"\"Constructor\n\n Args:\n ip_addr : IP address of the Sat-IP server.\n port : Sat-IP server's HTTP port.\n\n \"\"\"\n self.session = None\n self.local_addr = None\n self.params = None\n self.serving_fe = None\n\n if (ip_addr is not None):\n self.set_server_addr(ip_addr, port)\n else:\n self.base_url = None\n self.host = None","function_tokens":["def","__init__","(","self",",","ip_addr","=","None",",","port","=","8000",")",":","self",".","session","=","None","self",".","local_addr","=","None","self",".","params","=","None","self",".","serving_fe","=","None","if","(","ip_addr","is","not","None",")",":","self",".","set_server_addr","(","ip_addr",",","port",")","else",":","self",".","base_url","=","None","self",".","host","=","None"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L36-L53"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp._parse_fe_info","parameters":"(self, fe_info)","argument_list":"","return_statement":"return {\n 'lock': (lock, None),\n 'level': (signal_level, 'dBm'),\n 'quality': (quality, '%')\n }","docstring":"Parse frontend information returned by the server","docstring_summary":"Parse frontend information returned by the server","docstring_tokens":["Parse","frontend","information","returned","by","the","server"],"function":"def _parse_fe_info(self, fe_info):\n \"\"\"Parse frontend information returned by the server\"\"\"\n signal_level = ((10 * float(fe_info['sq'])) - 3440) \/ 48\n quality = float(fe_info['ber']) * 100 \/ 15\n lock = fe_info['ls'] == 'yes'\n # Note:\n # - The 'sq' metric is mapped to the signal level in dBm.\n # - The 'ber' value returned by the server (the antenna) is a number\n # from 0 to 15 related to the signal quality metric mentioned in\n # Section 3.5.7 of the Sat-IP specification.\n return {\n 'lock': (lock, None),\n 'level': (signal_level, 'dBm'),\n 'quality': (quality, '%')\n }","function_tokens":["def","_parse_fe_info","(","self",",","fe_info",")",":","signal_level","=","(","(","10","*","float","(","fe_info","[","'sq'","]",")",")","-","3440",")","\/","48","quality","=","float","(","fe_info","[","'ber'","]",")","*","100","\/","15","lock","=","fe_info","[","'ls'","]","==","'yes'","# Note:","# - The 'sq' metric is mapped to the signal level in dBm.","# - The 'ber' value returned by the server (the antenna) is a number","# from 0 to 15 related to the signal quality metric mentioned in","# Section 3.5.7 of the Sat-IP specification.","return","{","'lock'",":","(","lock",",","None",")",",","'level'",":","(","signal_level",",","'dBm'",")",",","'quality'",":","(","quality",",","'%'",")","}"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L55-L69"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp._set_from_ssdp_dev","parameters":"(self, dev)","argument_list":"","return_statement":"","docstring":"Set the base URL and host based on info discovered via SSDP","docstring_summary":"Set the base URL and host based on info discovered via SSDP","docstring_tokens":["Set","the","base","URL","and","host","based","on","info","discovered","via","SSDP"],"function":"def _set_from_ssdp_dev(self, dev):\n \"\"\"Set the base URL and host based on info discovered via SSDP\"\"\"\n self.base_url = dev['base_url']\n self.host = dev['host']","function_tokens":["def","_set_from_ssdp_dev","(","self",",","dev",")",":","self",".","base_url","=","dev","[","'base_url'","]","self",".","host","=","dev","[","'host'","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L71-L74"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp._assert_addr","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Assert that the Sat-IP device address has been discovered already","docstring_summary":"Assert that the Sat-IP device address has been discovered already","docstring_tokens":["Assert","that","the","Sat","-","IP","device","address","has","been","discovered","already"],"function":"def _assert_addr(self):\n \"\"\"Assert that the Sat-IP device address has been discovered already\"\"\"\n if (self.base_url is None):\n raise RuntimeError(\"Sat-IP device address must be discovered or \"\n \"informed first\")","function_tokens":["def","_assert_addr","(","self",")",":","if","(","self",".","base_url","is","None",")",":","raise","RuntimeError","(","\"Sat-IP device address must be discovered or \"","\"informed first\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L76-L80"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.set_dvbs2_params","parameters":"(self, info, target_modcod)","argument_list":"","return_statement":"","docstring":"Set the DVB-S2 and MPEG TS parameters of the target stream","docstring_summary":"Set the DVB-S2 and MPEG TS parameters of the target stream","docstring_tokens":["Set","the","DVB","-","S2","and","MPEG","TS","parameters","of","the","target","stream"],"function":"def set_dvbs2_params(self, info, target_modcod):\n \"\"\"Set the DVB-S2 and MPEG TS parameters of the target stream\"\"\"\n modcod = _parse_modcod(target_modcod)\n pilots = 'on' if defs.pilots else 'off'\n sym_rate = defs.sym_rate[info['sat']['alias']]\n self.params = {\n 'src': 1,\n 'freq': info['sat']['dl_freq'],\n 'pol': info['sat']['pol'].lower(),\n 'ro': defs.rolloff,\n 'msys': 'dvbs2',\n 'mtype': modcod['mtype'],\n 'plts': pilots,\n 'sr': int(sym_rate \/ 1e3),\n 'fec': modcod['fec'].replace('\/', ''),\n 'pids': \",\".join([str(pid) for pid in defs.pids])\n }","function_tokens":["def","set_dvbs2_params","(","self",",","info",",","target_modcod",")",":","modcod","=","_parse_modcod","(","target_modcod",")","pilots","=","'on'","if","defs",".","pilots","else","'off'","sym_rate","=","defs",".","sym_rate","[","info","[","'sat'","]","[","'alias'","]","]","self",".","params","=","{","'src'",":","1",",","'freq'",":","info","[","'sat'","]","[","'dl_freq'","]",",","'pol'",":","info","[","'sat'","]","[","'pol'","]",".","lower","(",")",",","'ro'",":","defs",".","rolloff",",","'msys'",":","'dvbs2'",",","'mtype'",":","modcod","[","'mtype'","]",",","'plts'",":","pilots",",","'sr'",":","int","(","sym_rate","\/","1e3",")",",","'fec'",":","modcod","[","'fec'","]",".","replace","(","'\/'",",","''",")",",","'pids'",":","\",\"",".","join","(","[","str","(","pid",")","for","pid","in","defs",".","pids","]",")","}"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L82-L98"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.set_server_addr","parameters":"(self, ip_addr, port=8000)","argument_list":"","return_statement":"","docstring":"Set the Sat-IP server address and the base URL for HTTP requests","docstring_summary":"Set the Sat-IP server address and the base URL for HTTP requests","docstring_tokens":["Set","the","Sat","-","IP","server","address","and","the","base","URL","for","HTTP","requests"],"function":"def set_server_addr(self, ip_addr, port=8000):\n \"\"\"Set the Sat-IP server address and the base URL for HTTP requests\"\"\"\n self.base_url = \"http:\/\/\" + ip_addr + \":\" + str(port)\n self.host = ip_addr","function_tokens":["def","set_server_addr","(","self",",","ip_addr",",","port","=","8000",")",":","self",".","base_url","=","\"http:\/\/\"","+","ip_addr","+","\":\"","+","str","(","port",")","self",".","host","=","ip_addr"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L100-L103"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.set_local_addr","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Find out which local address communicates with the Sat-IP server","docstring_summary":"Find out which local address communicates with the Sat-IP server","docstring_tokens":["Find","out","which","local","address","communicates","with","the","Sat","-","IP","server"],"function":"def set_local_addr(self):\n \"\"\"Find out which local address communicates with the Sat-IP server\"\"\"\n try:\n res = subprocess.check_output(['ip', 'route', 'get', self.host])\n except subprocess.CalledProcessError as e:\n logger.warning(\"Failed to read the local Sat-IP client address\")\n logger.warning(e)\n return\n\n out_line = res.decode().splitlines()[0].split()\n if (out_line[1] == \"via\" and len(out_line) > 6):\n local_addr = out_line[6]\n elif (len(out_line) > 4):\n local_addr = out_line[4]\n else:\n logger.warning(\"Failed to read the local Sat-IP client address\")\n return\n\n try:\n ip_address(local_addr)\n except ValueError as e:\n logger.warning(\"Failed to parse the local Sat-IP client address\")\n logger.warning(e)\n return\n logger.debug(\"Local Sat-IP client address: {}\".format(local_addr))\n self.local_addr = local_addr","function_tokens":["def","set_local_addr","(","self",")",":","try",":","res","=","subprocess",".","check_output","(","[","'ip'",",","'route'",",","'get'",",","self",".","host","]",")","except","subprocess",".","CalledProcessError","as","e",":","logger",".","warning","(","\"Failed to read the local Sat-IP client address\"",")","logger",".","warning","(","e",")","return","out_line","=","res",".","decode","(",")",".","splitlines","(",")","[","0","]",".","split","(",")","if","(","out_line","[","1","]","==","\"via\"","and","len","(","out_line",")",">","6",")",":","local_addr","=","out_line","[","6","]","elif","(","len","(","out_line",")",">","4",")",":","local_addr","=","out_line","[","4","]","else",":","logger",".","warning","(","\"Failed to read the local Sat-IP client address\"",")","return","try",":","ip_address","(","local_addr",")","except","ValueError","as","e",":","logger",".","warning","(","\"Failed to parse the local Sat-IP client address\"",")","logger",".","warning","(","e",")","return","logger",".","debug","(","\"Local Sat-IP client address: {}\"",".","format","(","local_addr",")",")","self",".","local_addr","=","local_addr"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L105-L130"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.discover","parameters":"(self, interactive=True, src_port=None, interface=None)","argument_list":"","return_statement":"","docstring":"Discover the Sat-IP receivers in the local network via UPnP","docstring_summary":"Discover the Sat-IP receivers in the local network via UPnP","docstring_tokens":["Discover","the","Sat","-","IP","receivers","in","the","local","network","via","UPnP"],"function":"def discover(self, interactive=True, src_port=None, interface=None):\n \"\"\"Discover the Sat-IP receivers in the local network via UPnP\"\"\"\n upnp = UPnP(src_port, interface)\n devices = upnp.discover()\n\n if (len(devices) == 0):\n return\n\n # Filter the Sat-IP devices\n sat_ip_devices = [{\n 'host': d.host,\n 'base_url': d.base_url\n } for d in devices if d.friendly_name == \"SELFSAT-IP\"]\n # Note: convert to dictionary so that _ask_multiple_choice can\n # deep-copy the selected element (which would not work for the original\n # SSDPDevice object).\n\n if (len(sat_ip_devices) == 0):\n return\n\n if (len(sat_ip_devices) > 1):\n if (not interactive):\n logger.warning(\"Found multiple Sat-IP receivers.\")\n logger.warning(\"Selecting the receiver at {}\".format(\n sat_ip_devices[0]['host']))\n logger.info(\n \"You can specify the receiver using option -a\/--addr or \"\n \"run in interactive mode\")\n self._set_from_ssdp_dev(sat_ip_devices[0])\n else:\n logger.info(\"Found multiple Sat-IP receivers.\")\n selected = util.ask_multiple_choice(\n sat_ip_devices,\n \"Select the Sat-IP receiver by IP address:\",\n \"Sat-IP receiver\",\n lambda x: \"Receiver at {}\".format(x['host']))\n self._set_from_ssdp_dev(selected)\n else:\n self._set_from_ssdp_dev(sat_ip_devices[0])","function_tokens":["def","discover","(","self",",","interactive","=","True",",","src_port","=","None",",","interface","=","None",")",":","upnp","=","UPnP","(","src_port",",","interface",")","devices","=","upnp",".","discover","(",")","if","(","len","(","devices",")","==","0",")",":","return","# Filter the Sat-IP devices","sat_ip_devices","=","[","{","'host'",":","d",".","host",",","'base_url'",":","d",".","base_url","}","for","d","in","devices","if","d",".","friendly_name","==","\"SELFSAT-IP\"","]","# Note: convert to dictionary so that _ask_multiple_choice can","# deep-copy the selected element (which would not work for the original","# SSDPDevice object).","if","(","len","(","sat_ip_devices",")","==","0",")",":","return","if","(","len","(","sat_ip_devices",")",">","1",")",":","if","(","not","interactive",")",":","logger",".","warning","(","\"Found multiple Sat-IP receivers.\"",")","logger",".","warning","(","\"Selecting the receiver at {}\"",".","format","(","sat_ip_devices","[","0","]","[","'host'","]",")",")","logger",".","info","(","\"You can specify the receiver using option -a\/--addr or \"","\"run in interactive mode\"",")","self",".","_set_from_ssdp_dev","(","sat_ip_devices","[","0","]",")","else",":","logger",".","info","(","\"Found multiple Sat-IP receivers.\"",")","selected","=","util",".","ask_multiple_choice","(","sat_ip_devices",",","\"Select the Sat-IP receiver by IP address:\"",",","\"Sat-IP receiver\"",",","lambda","x",":","\"Receiver at {}\"",".","format","(","x","[","'host'","]",")",")","self",".","_set_from_ssdp_dev","(","selected",")","else",":","self",".","_set_from_ssdp_dev","(","sat_ip_devices","[","0","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L132-L170"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.check_reachable","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Check if the Sat-IP server is reachable\n\n The server address could be specified directly instead of\n auto-discovered. Hence, it is worth double-checking the server can be\n reached by this client.\n\n Returns:\n Boolean indicating whether the Sat-IP server is reachable.","docstring_summary":"Check if the Sat-IP server is reachable","docstring_tokens":["Check","if","the","Sat","-","IP","server","is","reachable"],"function":"def check_reachable(self):\n \"\"\"Check if the Sat-IP server is reachable\n\n The server address could be specified directly instead of\n auto-discovered. Hence, it is worth double-checking the server can be\n reached by this client.\n\n Returns:\n Boolean indicating whether the Sat-IP server is reachable.\n\n \"\"\"\n self._assert_addr()\n\n try:\n r = requests.get(self.base_url)\n r.raise_for_status()\n except requests.exceptions.ConnectionError as errc:\n logger.error(\"Connection Error: {}\".format(errc))\n return False\n except requests.exceptions.HTTPError as errh:\n logger.error(\"HTTP Error: {}\".format(errh))\n return False\n except requests.exceptions.RequestException as err:\n logger.error(\"Error: {}\".format(err))\n return False\n\n return True","function_tokens":["def","check_reachable","(","self",")",":","self",".","_assert_addr","(",")","try",":","r","=","requests",".","get","(","self",".","base_url",")","r",".","raise_for_status","(",")","except","requests",".","exceptions",".","ConnectionError","as","errc",":","logger",".","error","(","\"Connection Error: {}\"",".","format","(","errc",")",")","return","False","except","requests",".","exceptions",".","HTTPError","as","errh",":","logger",".","error","(","\"HTTP Error: {}\"",".","format","(","errh",")",")","return","False","except","requests",".","exceptions",".","RequestException","as","err",":","logger",".","error","(","\"Error: {}\"",".","format","(","err",")",")","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L172-L198"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.check_fw_version","parameters":"(self, min_version=\"3.1.18\")","argument_list":"","return_statement":"return True","docstring":"Check if the Sat-IP server has the minimum required firmware version\n\n Returns:\n Boolean indicating whether the current firmware version satisfies\n the minimum required version. None if the attempt to read the\n current firmware version fails.","docstring_summary":"Check if the Sat-IP server has the minimum required firmware version","docstring_tokens":["Check","if","the","Sat","-","IP","server","has","the","minimum","required","firmware","version"],"function":"def check_fw_version(self, min_version=\"3.1.18\"):\n \"\"\"Check if the Sat-IP server has the minimum required firmware version\n\n Returns:\n Boolean indicating whether the current firmware version satisfies\n the minimum required version. None if the attempt to read the\n current firmware version fails.\n\n \"\"\"\n self._assert_addr()\n\n # Fetch the firmware version\n url = self.base_url + \"\/gmi_sw_ver.txt\"\n r = requests.get(url)\n try:\n r.raise_for_status()\n except requests.exceptions.HTTPError as e:\n logger.error(str(e))\n return None\n\n current_version = StrictVersion(r.text.strip('\\n'))\n if (current_version < StrictVersion(min_version)):\n logger.error(\"A firmware upgrade is required on the Sat-IP \"\n \"receiver.\")\n logger.info(\"The current firmware version is {}, but the minimum \"\n \"required version is {}.\".format(\n current_version, min_version))\n return False\n return True","function_tokens":["def","check_fw_version","(","self",",","min_version","=","\"3.1.18\"",")",":","self",".","_assert_addr","(",")","# Fetch the firmware version","url","=","self",".","base_url","+","\"\/gmi_sw_ver.txt\"","r","=","requests",".","get","(","url",")","try",":","r",".","raise_for_status","(",")","except","requests",".","exceptions",".","HTTPError","as","e",":","logger",".","error","(","str","(","e",")",")","return","None","current_version","=","StrictVersion","(","r",".","text",".","strip","(","'\\n'",")",")","if","(","current_version","<","StrictVersion","(","min_version",")",")",":","logger",".","error","(","\"A firmware upgrade is required on the Sat-IP \"","\"receiver.\"",")","logger",".","info","(","\"The current firmware version is {}, but the minimum \"","\"required version is {}.\"",".","format","(","current_version",",","min_version",")",")","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L200-L228"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.set_urllib3_logger_critical","parameters":"(func)","argument_list":"","return_statement":"return inner","docstring":"Wrapper to change the urllib3 logging level while calling func\n\n This function is meant to avoid the MissingHeaderBodySeparatorDefect\n error leading to urllib3.exceptions.HeaderParsingError when parsing the\n headers. The urllib3's logging level is restricted before calling the\n given function. Subsequently, it is restored to the original level.","docstring_summary":"Wrapper to change the urllib3 logging level while calling func","docstring_tokens":["Wrapper","to","change","the","urllib3","logging","level","while","calling","func"],"function":"def set_urllib3_logger_critical(func):\n \"\"\"Wrapper to change the urllib3 logging level while calling func\n\n This function is meant to avoid the MissingHeaderBodySeparatorDefect\n error leading to urllib3.exceptions.HeaderParsingError when parsing the\n headers. The urllib3's logging level is restricted before calling the\n given function. Subsequently, it is restored to the original level.\n\n \"\"\"\n def inner(*args, **kwargs):\n urllib3_logger = logging.getLogger('urllib3')\n urllib3_logging_level = urllib3_logger.level\n urllib3_logger.setLevel(logging.CRITICAL)\n r = func(*args, **kwargs)\n urllib3_logger.setLevel(urllib3_logging_level)\n return r\n\n return inner","function_tokens":["def","set_urllib3_logger_critical","(","func",")",":","def","inner","(","*","args",",","*","*","kwargs",")",":","urllib3_logger","=","logging",".","getLogger","(","'urllib3'",")","urllib3_logging_level","=","urllib3_logger",".","level","urllib3_logger",".","setLevel","(","logging",".","CRITICAL",")","r","=","func","(","*","args",",","*","*","kwargs",")","urllib3_logger",".","setLevel","(","urllib3_logging_level",")","return","r","return","inner"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L230-L247"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.upgrade_fw","parameters":"(self,\n cfg_dir,\n interactive=True,\n factory_default='0',\n no_wait=False)","argument_list":"","return_statement":"return True","docstring":"Upgrade the Selfsat Sat-IP antenna's firmware\n\n Args:\n cfg_dir : User's configuration directory.\n interactive : Whether to run in interactive mode.\n factory_default : Whether to restore the factory default configs.\n no_wait : Do not wait for the complete reboot in the end.\n\n Returns:\n Boolean indicating whether the upgrade was successful.","docstring_summary":"Upgrade the Selfsat Sat-IP antenna's firmware","docstring_tokens":["Upgrade","the","Selfsat","Sat","-","IP","antenna","s","firmware"],"function":"def upgrade_fw(self,\n cfg_dir,\n interactive=True,\n factory_default='0',\n no_wait=False):\n \"\"\"Upgrade the Selfsat Sat-IP antenna's firmware\n\n Args:\n cfg_dir : User's configuration directory.\n interactive : Whether to run in interactive mode.\n factory_default : Whether to restore the factory default configs.\n no_wait : Do not wait for the complete reboot in the end.\n\n Returns:\n Boolean indicating whether the upgrade was successful.\n\n \"\"\"\n self._assert_addr()\n\n if (interactive and not util.ask_yes_or_no(\"Proceed?\")):\n logger.info(\"Aborting\")\n return False\n\n logger.info(\"Upgrading the Sat-IP receiver's firmware.\")\n\n # Initialize the upgrade procedure\n resp = self._gmifu_req(params={'cmd': 'fu_cmd_init'})\n if (resp is None):\n return False\n\n init_resp = resp.json()\n logger.debug(\"Firmware upgrade init response:\")\n logger.debug(init_resp)\n if (init_resp['status'] != \"0\"):\n logger.error(\"({}) {}\".format(init_resp['status'],\n init_resp['desc']))\n return False\n\n # Download the latest firmware version\n filename = quote(\"SAT>IP UPGRADE FIRMWARE.zip\")\n download_url = os.path.join(\n (\"https:\/\/s3.ap-northeast-2.amazonaws.com\/\"\n \"logicsquare-seoul\/a64d56aa-567b-4053-bc84-12c2e58e46a6\/\"),\n filename)\n tmp_dir = os.path.join(cfg_dir, \"tmp\")\n download_dir = os.path.join(tmp_dir, \"sat-ip-fw\")\n\n if not os.path.exists(download_dir):\n os.makedirs(download_dir)\n\n logger.info(\"Downloading the latest firmware version...\")\n download_path = util.download_file(download_url,\n download_dir,\n dry_run=False,\n logger=logger)\n if (download_path is None):\n return False\n\n # Unzip the downloaded file\n with zipfile.ZipFile(download_path, 'r') as zip_ref:\n zip_ref.extractall(download_dir)\n\n # Find the software update .supg file:\n supg_files = glob.glob(os.path.join(download_dir, \"**\/*.supg\"),\n recursive=True)\n if (len(supg_files) > 1):\n logger.warning(\"Found multiple firmware update files\")\n logger.info(\"Selecting {}\".format(supg_files[0]))\n\n # Send the FW update file to the Sat-IP device\n logger.info(\"Uploading new firmware version to the Sat-IP server...\")\n resp = self._gmifu_req(\n params={\n 'cmd': 'fu_cmd_upload_file',\n 'val': 'update'\n },\n files={'fw_signed_updfile': open(supg_files[0], 'rb')})\n\n # Cleanup the temporary download directory\n shutil.rmtree(tmp_dir)\n\n if (resp is None):\n return False\n\n # Get the update info\n resp = self._gmifu_req(params={'cmd': 'fu_cmd_get_upd_info'})\n if (resp is None):\n return False\n\n # Parse\n update_info = resp.json()\n logger.debug(\"Update info:\")\n logger.debug(update_info)\n if ('thisver' not in update_info or 'newver' not in update_info):\n logger.error(\"Failed to parse the firmware update information\")\n return False\n this_sw_ver = StrictVersion(update_info['thisver']['sw_ver'])\n new_sw_ver = StrictVersion(update_info['newver']['sw_ver'])\n\n # Check if the download really contains a newer version\n if (this_sw_ver >= new_sw_ver):\n logger.error(\"Downloaded firmware update does not contain a more \"\n \"recent version.\")\n logger.info(\"Downloaded version {}, but the Sat-IP server is \"\n \"already running version {}.\".format(\n new_sw_ver, this_sw_ver))\n # Cancel the upgrade\n logger.info(\"Canceling the firmware upgrade.\")\n resp = self._gmifu_req(params={'cmd': 'fu_cmd_cancel_upd'})\n return False\n\n # Start the update\n logger.info(\n \"Upgrading firmware from version {} to version {}...\".format(\n this_sw_ver, new_sw_ver))\n resp = self._gmifu_req(params={\n 'cmd': 'fu_cmd_start_update',\n 'factdft': factory_default\n })\n if (resp is None):\n return False\n\n # Reboot in the end\n logger.info(\"Upgrade done. Rebooting...\")\n resp = self._gmifu_req(params={\n 'cmd': 'fu_cmd_reboot',\n 'factdft': factory_default\n })\n if (resp is None):\n return False\n\n # If so desired, wait until the device comes back\n if (no_wait):\n return True\n\n time.sleep(10)\n while (True):\n try:\n r = self._gmifu_req(method='get')\n if (r.ok):\n break\n except requests.exceptions.ConnectionError:\n time.sleep(1)\n\n return True","function_tokens":["def","upgrade_fw","(","self",",","cfg_dir",",","interactive","=","True",",","factory_default","=","'0'",",","no_wait","=","False",")",":","self",".","_assert_addr","(",")","if","(","interactive","and","not","util",".","ask_yes_or_no","(","\"Proceed?\"",")",")",":","logger",".","info","(","\"Aborting\"",")","return","False","logger",".","info","(","\"Upgrading the Sat-IP receiver's firmware.\"",")","# Initialize the upgrade procedure","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_init'","}",")","if","(","resp","is","None",")",":","return","False","init_resp","=","resp",".","json","(",")","logger",".","debug","(","\"Firmware upgrade init response:\"",")","logger",".","debug","(","init_resp",")","if","(","init_resp","[","'status'","]","!=","\"0\"",")",":","logger",".","error","(","\"({}) {}\"",".","format","(","init_resp","[","'status'","]",",","init_resp","[","'desc'","]",")",")","return","False","# Download the latest firmware version","filename","=","quote","(","\"SAT>IP UPGRADE FIRMWARE.zip\"",")","download_url","=","os",".","path",".","join","(","(","\"https:\/\/s3.ap-northeast-2.amazonaws.com\/\"","\"logicsquare-seoul\/a64d56aa-567b-4053-bc84-12c2e58e46a6\/\"",")",",","filename",")","tmp_dir","=","os",".","path",".","join","(","cfg_dir",",","\"tmp\"",")","download_dir","=","os",".","path",".","join","(","tmp_dir",",","\"sat-ip-fw\"",")","if","not","os",".","path",".","exists","(","download_dir",")",":","os",".","makedirs","(","download_dir",")","logger",".","info","(","\"Downloading the latest firmware version...\"",")","download_path","=","util",".","download_file","(","download_url",",","download_dir",",","dry_run","=","False",",","logger","=","logger",")","if","(","download_path","is","None",")",":","return","False","# Unzip the downloaded file","with","zipfile",".","ZipFile","(","download_path",",","'r'",")","as","zip_ref",":","zip_ref",".","extractall","(","download_dir",")","# Find the software update .supg file:","supg_files","=","glob",".","glob","(","os",".","path",".","join","(","download_dir",",","\"**\/*.supg\"",")",",","recursive","=","True",")","if","(","len","(","supg_files",")",">","1",")",":","logger",".","warning","(","\"Found multiple firmware update files\"",")","logger",".","info","(","\"Selecting {}\"",".","format","(","supg_files","[","0","]",")",")","# Send the FW update file to the Sat-IP device","logger",".","info","(","\"Uploading new firmware version to the Sat-IP server...\"",")","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_upload_file'",",","'val'",":","'update'","}",",","files","=","{","'fw_signed_updfile'",":","open","(","supg_files","[","0","]",",","'rb'",")","}",")","# Cleanup the temporary download directory","shutil",".","rmtree","(","tmp_dir",")","if","(","resp","is","None",")",":","return","False","# Get the update info","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_get_upd_info'","}",")","if","(","resp","is","None",")",":","return","False","# Parse","update_info","=","resp",".","json","(",")","logger",".","debug","(","\"Update info:\"",")","logger",".","debug","(","update_info",")","if","(","'thisver'","not","in","update_info","or","'newver'","not","in","update_info",")",":","logger",".","error","(","\"Failed to parse the firmware update information\"",")","return","False","this_sw_ver","=","StrictVersion","(","update_info","[","'thisver'","]","[","'sw_ver'","]",")","new_sw_ver","=","StrictVersion","(","update_info","[","'newver'","]","[","'sw_ver'","]",")","# Check if the download really contains a newer version","if","(","this_sw_ver",">=","new_sw_ver",")",":","logger",".","error","(","\"Downloaded firmware update does not contain a more \"","\"recent version.\"",")","logger",".","info","(","\"Downloaded version {}, but the Sat-IP server is \"","\"already running version {}.\"",".","format","(","new_sw_ver",",","this_sw_ver",")",")","# Cancel the upgrade","logger",".","info","(","\"Canceling the firmware upgrade.\"",")","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_cancel_upd'","}",")","return","False","# Start the update","logger",".","info","(","\"Upgrading firmware from version {} to version {}...\"",".","format","(","this_sw_ver",",","new_sw_ver",")",")","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_start_update'",",","'factdft'",":","factory_default","}",")","if","(","resp","is","None",")",":","return","False","# Reboot in the end","logger",".","info","(","\"Upgrade done. Rebooting...\"",")","resp","=","self",".","_gmifu_req","(","params","=","{","'cmd'",":","'fu_cmd_reboot'",",","'factdft'",":","factory_default","}",")","if","(","resp","is","None",")",":","return","False","# If so desired, wait until the device comes back","if","(","no_wait",")",":","return","True","time",".","sleep","(","10",")","while","(","True",")",":","try",":","r","=","self",".","_gmifu_req","(","method","=","'get'",")","if","(","r",".","ok",")",":","break","except","requests",".","exceptions",".","ConnectionError",":","time",".","sleep","(","1",")","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L264-L408"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.login","parameters":"(self, username=None, password=None)","argument_list":"","return_statement":"return success","docstring":"Login with the Sat-IP HTTP server","docstring_summary":"Login with the Sat-IP HTTP server","docstring_tokens":["Login","with","the","Sat","-","IP","HTTP","server"],"function":"def login(self, username=None, password=None):\n \"\"\"Login with the Sat-IP HTTP server\"\"\"\n self._assert_addr()\n # Cache the credentials to allow auto reconnection\n if (username is not None):\n self.username = username\n if (password is not None):\n self.password = password\n\n url = self.base_url + \"\/cgi-bin\/login.cgi\"\n self.session = requests.Session()\n r = self.session.post(url,\n data={\n 'cmd': 'login',\n 'username': self.username,\n 'password': self.password\n })\n r.raise_for_status()\n\n success = \"Error\" not in r.text\n if (not success):\n logger.debug(\"Login response:\")\n logger.debug(r.text)\n\n return success","function_tokens":["def","login","(","self",",","username","=","None",",","password","=","None",")",":","self",".","_assert_addr","(",")","# Cache the credentials to allow auto reconnection","if","(","username","is","not","None",")",":","self",".","username","=","username","if","(","password","is","not","None",")",":","self",".","password","=","password","url","=","self",".","base_url","+","\"\/cgi-bin\/login.cgi\"","self",".","session","=","requests",".","Session","(",")","r","=","self",".","session",".","post","(","url",",","data","=","{","'cmd'",":","'login'",",","'username'",":","self",".","username",",","'password'",":","self",".","password","}",")","r",".","raise_for_status","(",")","success","=","\"Error\"","not","in","r",".","text","if","(","not","success",")",":","logger",".","debug","(","\"Login response:\"",")","logger",".","debug","(","r",".","text",")","return","success"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L410-L434"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp._find_serving_frontend","parameters":"(self, active_frontends)","argument_list":"","return_statement":"","docstring":"Find the Sat-IP frontend serving this client\n\n Args:\n active_frontends (list): List of active frontends.","docstring_summary":"Find the Sat-IP frontend serving this client","docstring_tokens":["Find","the","Sat","-","IP","frontend","serving","this","client"],"function":"def _find_serving_frontend(self, active_frontends):\n \"\"\"Find the Sat-IP frontend serving this client\n\n Args:\n active_frontends (list): List of active frontends.\n\n \"\"\"\n\n # First, select the active frontends with matching DVB-S2 parameters.\n candidate_frontends = []\n for fe in active_frontends:\n try:\n fe_freq = float(fe['fq'])\n fe_pol = fe['pol']\n except ValueError:\n continue\n\n if fe_freq == self.params['freq'] and fe_pol == self.params['pol']:\n candidate_frontends.append(fe)\n\n # If there is only one matching frontend, it's got to be ours.\n if len(candidate_frontends) == 1:\n self.serving_fe = candidate_frontends[0]['name']\n return\n\n # If there isn't any candidate frontend at this point, warn the user.\n # There should be at least one matching frontend.\n if len(candidate_frontends) == 0:\n logger.warning(\n \"Could not find a frontend with matching parameters\")\n return\n\n # If there are multiple matching frontends (due to multiple clients),\n # try to select those serving the local IP address. However, note this\n # filtering may fail if the local address lies behind a NAT (e.g., a VM\n # behind a host NAT). In this case, the frontend client IP will be set\n # to the NAT address, not the local (translated) address.\n #\n # If none of the candidate frontends are serving the local address,\n # warn the user and skip this step, assuming it's the NAT case.\n if len(candidate_frontends) > 1:\n any_fe_serving_local_addr = any(\n [fe['ip'] == self.local_addr for fe in candidate_frontends])\n if any_fe_serving_local_addr:\n for fe in candidate_frontends.copy():\n if fe['ip'] != self.local_addr:\n candidate_frontends.remove(fe)\n else:\n logger.warning(\n \"Could not find a frontend serving the local {} address - \"\n \"logging the status of {}\".format(\n self.local_addr, candidate_frontends[-1]['name']))\n\n # In the end, despite the filtering, multiple candidate frontends could\n # remain. For example, in the NAT case mentioned above, where the IP\n # filtering is skipped. Alternatively, in case the same host is running\n # multiple clients. There is no protocol-level solution to detect which\n # client is which. The only workaround is to guess the frontend number\n # by inspecting the pre-existing active frontends before launching the\n # client. However, this is still a TODO. For now, pick the last\n # frontend from the list (possibly the most recent), and warn the user.\n self.serving_fe = candidate_frontends[-1]['name']\n n_candidate = len(candidate_frontends)\n if n_candidate > 1:\n logger.warning(\n \"The status logs can be unreliable when streaming from \"\n \"multiple frontends concurrently (found {} frontends, \"\n \"listening to {})\".format(n_candidate, self.serving_fe))","function_tokens":["def","_find_serving_frontend","(","self",",","active_frontends",")",":","# First, select the active frontends with matching DVB-S2 parameters.","candidate_frontends","=","[","]","for","fe","in","active_frontends",":","try",":","fe_freq","=","float","(","fe","[","'fq'","]",")","fe_pol","=","fe","[","'pol'","]","except","ValueError",":","continue","if","fe_freq","==","self",".","params","[","'freq'","]","and","fe_pol","==","self",".","params","[","'pol'","]",":","candidate_frontends",".","append","(","fe",")","# If there is only one matching frontend, it's got to be ours.","if","len","(","candidate_frontends",")","==","1",":","self",".","serving_fe","=","candidate_frontends","[","0","]","[","'name'","]","return","# If there isn't any candidate frontend at this point, warn the user.","# There should be at least one matching frontend.","if","len","(","candidate_frontends",")","==","0",":","logger",".","warning","(","\"Could not find a frontend with matching parameters\"",")","return","# If there are multiple matching frontends (due to multiple clients),","# try to select those serving the local IP address. However, note this","# filtering may fail if the local address lies behind a NAT (e.g., a VM","# behind a host NAT). In this case, the frontend client IP will be set","# to the NAT address, not the local (translated) address.","#","# If none of the candidate frontends are serving the local address,","# warn the user and skip this step, assuming it's the NAT case.","if","len","(","candidate_frontends",")",">","1",":","any_fe_serving_local_addr","=","any","(","[","fe","[","'ip'","]","==","self",".","local_addr","for","fe","in","candidate_frontends","]",")","if","any_fe_serving_local_addr",":","for","fe","in","candidate_frontends",".","copy","(",")",":","if","fe","[","'ip'","]","!=","self",".","local_addr",":","candidate_frontends",".","remove","(","fe",")","else",":","logger",".","warning","(","\"Could not find a frontend serving the local {} address - \"","\"logging the status of {}\"",".","format","(","self",".","local_addr",",","candidate_frontends","[","-","1","]","[","'name'","]",")",")","# In the end, despite the filtering, multiple candidate frontends could","# remain. For example, in the NAT case mentioned above, where the IP","# filtering is skipped. Alternatively, in case the same host is running","# multiple clients. There is no protocol-level solution to detect which","# client is which. The only workaround is to guess the frontend number","# by inspecting the pre-existing active frontends before launching the","# client. However, this is still a TODO. For now, pick the last","# frontend from the list (possibly the most recent), and warn the user.","self",".","serving_fe","=","candidate_frontends","[","-","1","]","[","'name'","]","n_candidate","=","len","(","candidate_frontends",")","if","n_candidate",">","1",":","logger",".","warning","(","\"The status logs can be unreliable when streaming from \"","\"multiple frontends concurrently (found {} frontends, \"","\"listening to {})\"",".","format","(","n_candidate",",","self",".","serving_fe",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L436-L503"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/satip.py","language":"python","identifier":"SatIp.fe_stats","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read DVB-S2 frontend stats\n\n Returns:\n\n (dict): Dictionary with the frontend status in case the reading is\n successful. None on the following error conditions: 1) if the\n Sat-IP server does not return any frontend info; 2) if the frontend\n serving this client is not active in the Sat-IP server; and 3) if\n the frontend status parsing fails.","docstring_summary":"Read DVB-S2 frontend stats","docstring_tokens":["Read","DVB","-","S2","frontend","stats"],"function":"def fe_stats(self):\n \"\"\"Read DVB-S2 frontend stats\n\n Returns:\n\n (dict): Dictionary with the frontend status in case the reading is\n successful. None on the following error conditions: 1) if the\n Sat-IP server does not return any frontend info; 2) if the frontend\n serving this client is not active in the Sat-IP server; and 3) if\n the frontend status parsing fails.\n\n \"\"\"\n self._assert_addr()\n url = self.base_url + \"\/cgi-bin\/index.cgi\"\n\n try:\n rv = self.session.get(url, params={'cmd': 'frontend_info'})\n except requests.exceptions.ConnectionError as errc:\n logger.error(\"Connection Error: {}\".format(errc))\n logger.info(\"Reconnecting\")\n self.login()\n return\n except requests.exceptions.HTTPError as errh:\n logger.error(\"HTTP Error: {}\".format(errh))\n logger.info(\"Reconnecting\")\n self.login()\n return\n except requests.exceptions.RequestException as err:\n logger.error(\"Error: {}\".format(err))\n logger.info(\"Reconnecting\")\n self.login()\n return\n\n try:\n info = rv.json()\n except ValueError:\n if (\"\/cgi-bin\/login.cgi\" in rv.text and rv.status_code == 200):\n logger.warning(\"Sat-IP server has closed the session. \"\n \"Reconnecting.\")\n self.login()\n return\n\n if 'frontends' not in info:\n return\n\n # Select the active frontends:\n active_frontends = []\n for fe in info['frontends']:\n if fe['frontend']['ip'] != 'none' and fe['frontend']['ip'] != 'NA':\n active_frontends.append(fe['frontend'])\n\n if len(active_frontends) == 0:\n logger.warning(\"Could not find any active frontend\")\n return\n\n logger.debug(\"Active frontends: {}\".format(active_frontends))\n\n # Define the active frontend serving this client\n if (self.serving_fe is None):\n self._find_serving_frontend(active_frontends)\n\n # Check that the serving frontend is still in the active frontend list.\n # If not, there are two possible reasons:\n #\n # 1) We are running with option --ignore-http-errors and the tsp client\n # has just reconnected.\n # 2) The initial procedure to find the serving frontend got confused\n # due to other Sat-IP clients running on the same host and was\n # actually pointing to a frontend serving another client. Now, this\n # other client stopped and the frontend is no longer active.\n #\n # In any case, try to find the serving frontend again.\n if not any([fe['name'] == self.serving_fe for fe in active_frontends]):\n logger.warning(\"Sat-IP {} has become inactive.\".format(\n self.serving_fe))\n self._find_serving_frontend(active_frontends)\n if (self.serving_fe is not None):\n logger.info(\"Switching to {}\".format(self.serving_fe))\n\n # Finally, parse the status from the serving frontend.\n serving_fe = [\n fe for fe in active_frontends if fe['name'] == self.serving_fe\n ]\n if len(serving_fe) == 0:\n return\n\n try:\n return self._parse_fe_info(serving_fe[0])\n except ValueError:\n return","function_tokens":["def","fe_stats","(","self",")",":","self",".","_assert_addr","(",")","url","=","self",".","base_url","+","\"\/cgi-bin\/index.cgi\"","try",":","rv","=","self",".","session",".","get","(","url",",","params","=","{","'cmd'",":","'frontend_info'","}",")","except","requests",".","exceptions",".","ConnectionError","as","errc",":","logger",".","error","(","\"Connection Error: {}\"",".","format","(","errc",")",")","logger",".","info","(","\"Reconnecting\"",")","self",".","login","(",")","return","except","requests",".","exceptions",".","HTTPError","as","errh",":","logger",".","error","(","\"HTTP Error: {}\"",".","format","(","errh",")",")","logger",".","info","(","\"Reconnecting\"",")","self",".","login","(",")","return","except","requests",".","exceptions",".","RequestException","as","err",":","logger",".","error","(","\"Error: {}\"",".","format","(","err",")",")","logger",".","info","(","\"Reconnecting\"",")","self",".","login","(",")","return","try",":","info","=","rv",".","json","(",")","except","ValueError",":","if","(","\"\/cgi-bin\/login.cgi\"","in","rv",".","text","and","rv",".","status_code","==","200",")",":","logger",".","warning","(","\"Sat-IP server has closed the session. \"","\"Reconnecting.\"",")","self",".","login","(",")","return","if","'frontends'","not","in","info",":","return","# Select the active frontends:","active_frontends","=","[","]","for","fe","in","info","[","'frontends'","]",":","if","fe","[","'frontend'","]","[","'ip'","]","!=","'none'","and","fe","[","'frontend'","]","[","'ip'","]","!=","'NA'",":","active_frontends",".","append","(","fe","[","'frontend'","]",")","if","len","(","active_frontends",")","==","0",":","logger",".","warning","(","\"Could not find any active frontend\"",")","return","logger",".","debug","(","\"Active frontends: {}\"",".","format","(","active_frontends",")",")","# Define the active frontend serving this client","if","(","self",".","serving_fe","is","None",")",":","self",".","_find_serving_frontend","(","active_frontends",")","# Check that the serving frontend is still in the active frontend list.","# If not, there are two possible reasons:","#","# 1) We are running with option --ignore-http-errors and the tsp client","# has just reconnected.","# 2) The initial procedure to find the serving frontend got confused","# due to other Sat-IP clients running on the same host and was","# actually pointing to a frontend serving another client. Now, this","# other client stopped and the frontend is no longer active.","#","# In any case, try to find the serving frontend again.","if","not","any","(","[","fe","[","'name'","]","==","self",".","serving_fe","for","fe","in","active_frontends","]",")",":","logger",".","warning","(","\"Sat-IP {} has become inactive.\"",".","format","(","self",".","serving_fe",")",")","self",".","_find_serving_frontend","(","active_frontends",")","if","(","self",".","serving_fe","is","not","None",")",":","logger",".","info","(","\"Switching to {}\"",".","format","(","self",".","serving_fe",")",")","# Finally, parse the status from the serving frontend.","serving_fe","=","[","fe","for","fe","in","active_frontends","if","fe","[","'name'","]","==","self",".","serving_fe","]","if","len","(","serving_fe",")","==","0",":","return","try",":","return","self",".","_parse_fe_info","(","serving_fe","[","0","]",")","except","ValueError",":","return"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/satip.py#L505-L594"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_check_debian_net_interfaces_d","parameters":"(dry)","argument_list":"","return_statement":"","docstring":"Check if \/etc\/network\/interfaces.d\/ is included as source-directory\n\n If the distribution doesn't have the `\/etc\/network\/interface` directory,\n just return.","docstring_summary":"Check if \/etc\/network\/interfaces.d\/ is included as source-directory","docstring_tokens":["Check","if","\/","etc","\/","network","\/","interfaces",".","d","\/","is","included","as","source","-","directory"],"function":"def _check_debian_net_interfaces_d(dry):\n \"\"\"Check if \/etc\/network\/interfaces.d\/ is included as source-directory\n\n If the distribution doesn't have the `\/etc\/network\/interface` directory,\n just return.\n\n \"\"\"\n if_file = \"\/etc\/network\/interfaces\"\n\n if (not os.path.exists(if_file)):\n return\n\n if_dir = \"\/etc\/network\/interfaces.d\/\"\n src_line = \"source \/etc\/network\/interfaces.d\/*\"\n\n if (dry):\n util.fill_print(\n \"Make sure directory \\\"{}\\\" is considered as source for network \"\n \"interface configurations. Check if your \\\"{}\\\" file contains \"\n \"the following line:\".format(if_dir, if_file))\n print(\"\\n{}\\n\".format(src_line))\n print(\"If not, add it.\\n\")\n return\n\n with open(if_file) as fd:\n current_cfg = fd.read()\n\n src_included = False\n for line in current_cfg.splitlines():\n if src_line in line:\n src_included = True\n break\n\n if (src_included):\n return\n\n with open(if_file, 'a') as fd:\n fd.write(\"\\n\" + src_line)","function_tokens":["def","_check_debian_net_interfaces_d","(","dry",")",":","if_file","=","\"\/etc\/network\/interfaces\"","if","(","not","os",".","path",".","exists","(","if_file",")",")",":","return","if_dir","=","\"\/etc\/network\/interfaces.d\/\"","src_line","=","\"source \/etc\/network\/interfaces.d\/*\"","if","(","dry",")",":","util",".","fill_print","(","\"Make sure directory \\\"{}\\\" is considered as source for network \"","\"interface configurations. Check if your \\\"{}\\\" file contains \"","\"the following line:\"",".","format","(","if_dir",",","if_file",")",")","print","(","\"\\n{}\\n\"",".","format","(","src_line",")",")","print","(","\"If not, add it.\\n\"",")","return","with","open","(","if_file",")","as","fd",":","current_cfg","=","fd",".","read","(",")","src_included","=","False","for","line","in","current_cfg",".","splitlines","(",")",":","if","src_line","in","line",":","src_included","=","True","break","if","(","src_included",")",":","return","with","open","(","if_file",",","'a'",")","as","fd",":","fd",".","write","(","\"\\n\"","+","src_line",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L15-L52"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_add_to_netplan","parameters":"(ifname, addr_with_prefix)","argument_list":"","return_statement":"","docstring":"Create configuration file at \/etc\/netplan\/","docstring_summary":"Create configuration file at \/etc\/netplan\/","docstring_tokens":["Create","configuration","file","at","\/","etc","\/","netplan","\/"],"function":"def _add_to_netplan(ifname, addr_with_prefix):\n \"\"\"Create configuration file at \/etc\/netplan\/\"\"\"\n assert (\"\/\" in addr_with_prefix)\n cfg_dir = \"\/etc\/netplan\/\"\n\n cfg = (\"network:\\n\"\n \" version: 2\\n\"\n \" renderer: networkd\\n\"\n \" ethernets:\\n\"\n \" {0}:\\n\"\n \" dhcp4: no\\n\"\n \" optional: true\\n\"\n \" addresses: [{1}]\\n\").format(ifname, addr_with_prefix)\n\n fname = \"blocksat-\" + ifname + \".yaml\"\n path = os.path.join(cfg_dir, fname)\n\n if (runner.dry):\n util.fill_print(\"Create a file named {} at {} and add the \"\n \"following to it:\".format(fname, cfg_dir))\n print(cfg)\n return\n\n runner.create_file(cfg, path, root=True)","function_tokens":["def","_add_to_netplan","(","ifname",",","addr_with_prefix",")",":","assert","(","\"\/\"","in","addr_with_prefix",")","cfg_dir","=","\"\/etc\/netplan\/\"","cfg","=","(","\"network:\\n\"","\" version: 2\\n\"","\" renderer: networkd\\n\"","\" ethernets:\\n\"","\" {0}:\\n\"","\" dhcp4: no\\n\"","\" optional: true\\n\"","\" addresses: [{1}]\\n\"",")",".","format","(","ifname",",","addr_with_prefix",")","fname","=","\"blocksat-\"","+","ifname","+","\".yaml\"","path","=","os",".","path",".","join","(","cfg_dir",",","fname",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"Create a file named {} at {} and add the \"","\"following to it:\"",".","format","(","fname",",","cfg_dir",")",")","print","(","cfg",")","return","runner",".","create_file","(","cfg",",","path",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L55-L78"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_add_to_interfaces_d","parameters":"(ifname, addr, netmask)","argument_list":"","return_statement":"","docstring":"Create configuration file at \/etc\/network\/interfaces.d\/","docstring_summary":"Create configuration file at \/etc\/network\/interfaces.d\/","docstring_tokens":["Create","configuration","file","at","\/","etc","\/","network","\/","interfaces",".","d","\/"],"function":"def _add_to_interfaces_d(ifname, addr, netmask):\n \"\"\"Create configuration file at \/etc\/network\/interfaces.d\/\"\"\"\n if_dir = \"\/etc\/network\/interfaces.d\/\"\n cfg = (\"iface {0} inet static\\n\"\n \" address {1}\\n\"\n \" netmask {2}\\n\").format(ifname, addr, netmask)\n fname = ifname + \".conf\"\n path = os.path.join(if_dir, fname)\n\n if (runner.dry):\n util.fill_print(\"Create a file named {} at {} and add the \"\n \"following to it:\".format(fname, if_dir))\n print(cfg)\n return\n\n runner.create_file(cfg, path, root=True)","function_tokens":["def","_add_to_interfaces_d","(","ifname",",","addr",",","netmask",")",":","if_dir","=","\"\/etc\/network\/interfaces.d\/\"","cfg","=","(","\"iface {0} inet static\\n\"","\" address {1}\\n\"","\" netmask {2}\\n\"",")",".","format","(","ifname",",","addr",",","netmask",")","fname","=","ifname","+","\".conf\"","path","=","os",".","path",".","join","(","if_dir",",","fname",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"Create a file named {} at {} and add the \"","\"following to it:\"",".","format","(","fname",",","if_dir",")",")","print","(","cfg",")","return","runner",".","create_file","(","cfg",",","path",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L81-L96"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_add_to_sysconfig_net_scripts","parameters":"(ifname, addr, netmask)","argument_list":"","return_statement":"","docstring":"Create configuration file at \/etc\/sysconfig\/network-scripts\/","docstring_summary":"Create configuration file at \/etc\/sysconfig\/network-scripts\/","docstring_tokens":["Create","configuration","file","at","\/","etc","\/","sysconfig","\/","network","-","scripts","\/"],"function":"def _add_to_sysconfig_net_scripts(ifname, addr, netmask):\n \"\"\"Create configuration file at \/etc\/sysconfig\/network-scripts\/\"\"\"\n cfg_dir = \"\/etc\/sysconfig\/network-scripts\/\"\n cfg = (\"NM_CONTROLLED=\\\"yes\\\"\\n\"\n \"DEVICE=\\\"{0}\\\"\\n\"\n \"BOOTPROTO=none\\n\"\n \"ONBOOT=\\\"no\\\"\\n\"\n \"IPADDR={1}\\n\"\n \"NETMASK={2}\\n\").format(ifname, addr, netmask)\n\n fname = \"ifcfg-\" + ifname\n path = os.path.join(cfg_dir, fname)\n\n if (runner.dry):\n util.fill_print(\"Create a file named {} at {} and add the \"\n \"following to it:\".format(fname, cfg_dir))\n print(cfg)\n return\n\n runner.create_file(cfg, path, root=True)","function_tokens":["def","_add_to_sysconfig_net_scripts","(","ifname",",","addr",",","netmask",")",":","cfg_dir","=","\"\/etc\/sysconfig\/network-scripts\/\"","cfg","=","(","\"NM_CONTROLLED=\\\"yes\\\"\\n\"","\"DEVICE=\\\"{0}\\\"\\n\"","\"BOOTPROTO=none\\n\"","\"ONBOOT=\\\"no\\\"\\n\"","\"IPADDR={1}\\n\"","\"NETMASK={2}\\n\"",")",".","format","(","ifname",",","addr",",","netmask",")","fname","=","\"ifcfg-\"","+","ifname","path","=","os",".","path",".","join","(","cfg_dir",",","fname",")","if","(","runner",".","dry",")",":","util",".","fill_print","(","\"Create a file named {} at {} and add the \"","\"following to it:\"",".","format","(","fname",",","cfg_dir",")",")","print","(","cfg",")","return","runner",".","create_file","(","cfg",",","path",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L99-L118"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_set_static_iface_ip","parameters":"(ifname, ipv4_if)","argument_list":"","return_statement":"","docstring":"Set static IP address for target network interface\n\n Args:\n ifname : Network device name\n ipv4_if : IPv4Interface object with the target interface address","docstring_summary":"Set static IP address for target network interface","docstring_tokens":["Set","static","IP","address","for","target","network","interface"],"function":"def _set_static_iface_ip(ifname, ipv4_if):\n \"\"\"Set static IP address for target network interface\n\n Args:\n ifname : Network device name\n ipv4_if : IPv4Interface object with the target interface address\n\n \"\"\"\n isinstance(ipv4_if, IPv4Interface)\n addr = str(ipv4_if.ip)\n addr_with_prefix = ipv4_if.with_prefixlen\n netmask = str(ipv4_if.netmask)\n\n if (which(\"netplan\") is not None):\n _add_to_netplan(ifname, addr_with_prefix)\n elif (os.path.exists(\"\/etc\/network\/interfaces.d\/\")):\n _add_to_interfaces_d(ifname, addr, netmask)\n elif (os.path.exists(\"\/etc\/sysconfig\/network-scripts\")):\n _add_to_sysconfig_net_scripts(ifname, addr, netmask)\n else:\n logger.warning(\"Falling back to \\\"ip addr add\\\" command\")\n runner.run([\"ip\", \"addr\", \"add\", addr_with_prefix, \"dev\", ifname],\n root=True)","function_tokens":["def","_set_static_iface_ip","(","ifname",",","ipv4_if",")",":","isinstance","(","ipv4_if",",","IPv4Interface",")","addr","=","str","(","ipv4_if",".","ip",")","addr_with_prefix","=","ipv4_if",".","with_prefixlen","netmask","=","str","(","ipv4_if",".","netmask",")","if","(","which","(","\"netplan\"",")","is","not","None",")",":","_add_to_netplan","(","ifname",",","addr_with_prefix",")","elif","(","os",".","path",".","exists","(","\"\/etc\/network\/interfaces.d\/\"",")",")",":","_add_to_interfaces_d","(","ifname",",","addr",",","netmask",")","elif","(","os",".","path",".","exists","(","\"\/etc\/sysconfig\/network-scripts\"",")",")",":","_add_to_sysconfig_net_scripts","(","ifname",",","addr",",","netmask",")","else",":","logger",".","warning","(","\"Falling back to \\\"ip addr add\\\" command\"",")","runner",".","run","(","[","\"ip\"",",","\"addr\"",",","\"add\"",",","addr_with_prefix",",","\"dev\"",",","ifname","]",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L121-L143"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_check_ip","parameters":"(net_if, ip_addr)","argument_list":"","return_statement":"return has_ip, ip_ok","docstring":"Check if interface has IP and if it matches target IP\n\n Args:\n net_if : DVB network interface name\n ip_addr : Target IP address for the DVB interface slash subnet mask\n\n Returns:\n (Bool, Bool) Tuple of booleans. The first indicates whether interface\n already has an IP. The second indicates whether the interface IP (if\n existing) matches with respect to a target IP.","docstring_summary":"Check if interface has IP and if it matches target IP","docstring_tokens":["Check","if","interface","has","IP","and","if","it","matches","target","IP"],"function":"def _check_ip(net_if, ip_addr):\n \"\"\"Check if interface has IP and if it matches target IP\n\n Args:\n net_if : DVB network interface name\n ip_addr : Target IP address for the DVB interface slash subnet mask\n\n Returns:\n (Bool, Bool) Tuple of booleans. The first indicates whether interface\n already has an IP. The second indicates whether the interface IP (if\n existing) matches with respect to a target IP.\n\n \"\"\"\n try:\n res = subprocess.check_output([\"ip\", \"addr\", \"show\", \"dev\", net_if],\n stderr=subprocess.DEVNULL)\n except subprocess.CalledProcessError:\n return False, False\n\n has_ip = False\n ip_ok = False\n for line in res.splitlines():\n if \"inet\" in line.decode() and \"inet6\" not in line.decode():\n has_ip = True\n # Check if IP matches target\n inet_info = line.decode().split()\n inet_if = IPv4Interface(inet_info[1])\n target_if = IPv4Interface(ip_addr)\n ip_ok = (inet_if == target_if)\n break\n\n return has_ip, ip_ok","function_tokens":["def","_check_ip","(","net_if",",","ip_addr",")",":","try",":","res","=","subprocess",".","check_output","(","[","\"ip\"",",","\"addr\"",",","\"show\"",",","\"dev\"",",","net_if","]",",","stderr","=","subprocess",".","DEVNULL",")","except","subprocess",".","CalledProcessError",":","return","False",",","False","has_ip","=","False","ip_ok","=","False","for","line","in","res",".","splitlines","(",")",":","if","\"inet\"","in","line",".","decode","(",")","and","\"inet6\"","not","in","line",".","decode","(",")",":","has_ip","=","True","# Check if IP matches target","inet_info","=","line",".","decode","(",")",".","split","(",")","inet_if","=","IPv4Interface","(","inet_info","[","1","]",")","target_if","=","IPv4Interface","(","ip_addr",")","ip_ok","=","(","inet_if","==","target_if",")","break","return","has_ip",",","ip_ok"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L146-L177"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"_set_ip","parameters":"(net_if, ip_addr, verbose)","argument_list":"","return_statement":"","docstring":"Set the IP of the DVB network interface\n\n Args:\n net_if : DVB network interface name\n ip_addr : Target IP address for the DVB interface slash subnet mask\n verbose : Controls verbosity","docstring_summary":"Set the IP of the DVB network interface","docstring_tokens":["Set","the","IP","of","the","DVB","network","interface"],"function":"def _set_ip(net_if, ip_addr, verbose):\n \"\"\"Set the IP of the DVB network interface\n\n Args:\n net_if : DVB network interface name\n ip_addr : Target IP address for the DVB interface slash subnet mask\n verbose : Controls verbosity\n\n \"\"\"\n inet_if = IPv4Interface(ip_addr)\n\n # Flush previous IP\n if (runner.dry):\n print(\"Flush any IP address from interface {}:\\n\".format(net_if))\n runner.run([\"ip\", \"address\", \"flush\", \"dev\", net_if], root=True)\n if (runner.dry):\n print()\n\n # Configure new static IP\n _set_static_iface_ip(net_if, inet_if)","function_tokens":["def","_set_ip","(","net_if",",","ip_addr",",","verbose",")",":","inet_if","=","IPv4Interface","(","ip_addr",")","# Flush previous IP","if","(","runner",".","dry",")",":","print","(","\"Flush any IP address from interface {}:\\n\"",".","format","(","net_if",")",")","runner",".","run","(","[","\"ip\"",",","\"address\"",",","\"flush\"",",","\"dev\"",",","net_if","]",",","root","=","True",")","if","(","runner",".","dry",")",":","print","(",")","# Configure new static IP","_set_static_iface_ip","(","net_if",",","inet_if",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L180-L199"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"set_ips","parameters":"(net_ifs, ip_addrs, verbose=True, dry=False)","argument_list":"","return_statement":"","docstring":"Set IPs of one or multiple DVB network interface(s\n\n Args:\n net_ifs : List of DVB network interface names\n ip_addrs : List of IP addresses for the dvbnet interface's subnet mask\n verbose : Controls verbosity\n dry : Dry run mode","docstring_summary":"Set IPs of one or multiple DVB network interface(s","docstring_tokens":["Set","IPs","of","one","or","multiple","DVB","network","interface","(","s"],"function":"def set_ips(net_ifs, ip_addrs, verbose=True, dry=False):\n \"\"\"Set IPs of one or multiple DVB network interface(s\n\n Args:\n net_ifs : List of DVB network interface names\n ip_addrs : List of IP addresses for the dvbnet interface's subnet mask\n verbose : Controls verbosity\n dry : Dry run mode\n\n \"\"\"\n runner.set_dry(dry)\n\n if (verbose):\n util.print_header(\"Interface IP Address\")\n\n if (dry):\n print(\"Configure a static IP address on the dvbnet interface.\\n\")\n\n # Configure static IP addresses\n if (which(\"netplan\") is None):\n _check_debian_net_interfaces_d(dry)\n\n for net_if, ip_addr in zip(net_ifs, ip_addrs):\n _set_ip(net_if, ip_addr, verbose)\n\n # Bring up interfaces\n ifup_required = False\n if (which(\"netplan\") is not None):\n if (dry):\n print(\"Finally, apply the new netplan configuration:\\n\")\n runner.run([\"netplan\", \"apply\"], root=True)\n elif (os.path.exists(\"\/etc\/network\/interfaces.d\/\")):\n ifup_required = True\n # Debian approach\n if (dry):\n util.fill_print(\"Finally, restart the networking service and \"\n \"bring up the interfaces:\")\n print()\n runner.run([\"systemctl\", \"restart\", \"networking\"], root=True)\n elif (os.path.exists(\"\/etc\/sysconfig\/network-scripts\")):\n ifup_required = True\n # CentOS\/Fedora\/RHEL approach\n if (dry):\n print(textwrap.fill(\"Finally, bring up the interfaces:\") + \"\\n\")\n\n if (ifup_required):\n for net_if in net_ifs:\n runner.run([\"ifup\", net_if], root=True)","function_tokens":["def","set_ips","(","net_ifs",",","ip_addrs",",","verbose","=","True",",","dry","=","False",")",":","runner",".","set_dry","(","dry",")","if","(","verbose",")",":","util",".","print_header","(","\"Interface IP Address\"",")","if","(","dry",")",":","print","(","\"Configure a static IP address on the dvbnet interface.\\n\"",")","# Configure static IP addresses","if","(","which","(","\"netplan\"",")","is","None",")",":","_check_debian_net_interfaces_d","(","dry",")","for","net_if",",","ip_addr","in","zip","(","net_ifs",",","ip_addrs",")",":","_set_ip","(","net_if",",","ip_addr",",","verbose",")","# Bring up interfaces","ifup_required","=","False","if","(","which","(","\"netplan\"",")","is","not","None",")",":","if","(","dry",")",":","print","(","\"Finally, apply the new netplan configuration:\\n\"",")","runner",".","run","(","[","\"netplan\"",",","\"apply\"","]",",","root","=","True",")","elif","(","os",".","path",".","exists","(","\"\/etc\/network\/interfaces.d\/\"",")",")",":","ifup_required","=","True","# Debian approach","if","(","dry",")",":","util",".","fill_print","(","\"Finally, restart the networking service and \"","\"bring up the interfaces:\"",")","print","(",")","runner",".","run","(","[","\"systemctl\"",",","\"restart\"",",","\"networking\"","]",",","root","=","True",")","elif","(","os",".","path",".","exists","(","\"\/etc\/sysconfig\/network-scripts\"",")",")",":","ifup_required","=","True","# CentOS\/Fedora\/RHEL approach","if","(","dry",")",":","print","(","textwrap",".","fill","(","\"Finally, bring up the interfaces:\"",")","+","\"\\n\"",")","if","(","ifup_required",")",":","for","net_if","in","net_ifs",":","runner",".","run","(","[","\"ifup\"",",","net_if","]",",","root","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L202-L249"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"check_ips","parameters":"(net_ifs, ip_addrs)","argument_list":"","return_statement":"","docstring":"Check if IPs of one or multiple DVB network interface(s) are OK\n\n Args:\n net_ifs : List of DVB network interface names\n ip_addrs : List of IP addresses for the dvbnet interface's subnet mask\n verbose : Controls verbosity","docstring_summary":"Check if IPs of one or multiple DVB network interface(s) are OK","docstring_tokens":["Check","if","IPs","of","one","or","multiple","DVB","network","interface","(","s",")","are","OK"],"function":"def check_ips(net_ifs, ip_addrs):\n \"\"\"Check if IPs of one or multiple DVB network interface(s) are OK\n\n Args:\n net_ifs : List of DVB network interface names\n ip_addrs : List of IP addresses for the dvbnet interface's subnet mask\n verbose : Controls verbosity\n\n \"\"\"\n for net_if, ip_addr in zip(net_ifs, ip_addrs):\n has_ip, ip_ok = _check_ip(net_if, ip_addr)\n if (not has_ip):\n raise ValueError(\n \"Interface {} does not have an IP address\".format(net_if))\n elif (has_ip and not ip_ok):\n raise ValueError(\"Interface {} IP is not {}\".format(\n net_if, ip_addr))","function_tokens":["def","check_ips","(","net_ifs",",","ip_addrs",")",":","for","net_if",",","ip_addr","in","zip","(","net_ifs",",","ip_addrs",")",":","has_ip",",","ip_ok","=","_check_ip","(","net_if",",","ip_addr",")","if","(","not","has_ip",")",":","raise","ValueError","(","\"Interface {} does not have an IP address\"",".","format","(","net_if",")",")","elif","(","has_ip","and","not","ip_ok",")",":","raise","ValueError","(","\"Interface {} IP is not {}\"",".","format","(","net_if",",","ip_addr",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L252-L268"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"rm_ip","parameters":"(ifname, dry=False)","argument_list":"","return_statement":"","docstring":"Remove the static IP configuration of a given interface","docstring_summary":"Remove the static IP configuration of a given interface","docstring_tokens":["Remove","the","static","IP","configuration","of","a","given","interface"],"function":"def rm_ip(ifname, dry=False):\n \"\"\"Remove the static IP configuration of a given interface\"\"\"\n runner.set_dry(dry)\n\n # Remove conf file for network interface (next time the interface could\n # have a different number)\n netplan_file = os.path.join(\"\/etc\/netplan\/\",\n \"blocksat-\" + ifname + \".yaml\")\n net_file = os.path.join(\"\/etc\/network\/interfaces.d\/\", ifname + \".conf\")\n ifcfg_file = os.path.join(\"\/etc\/sysconfig\/network-scripts\/\",\n \"ifcfg-\" + ifname)\n\n if (which(\"netplan\") is not None):\n cfg_file = netplan_file\n elif (os.path.exists(net_file)):\n cfg_file = net_file\n elif (os.path.exists(ifcfg_file)):\n cfg_file = ifcfg_file\n else:\n cfg_file = None\n\n if (cfg_file is not None and os.path.exists(cfg_file)):\n runner.run([\"rm\", cfg_file], root=True)\n if (not dry):\n logger.info(\"Removed configuration file {}\".format(cfg_file))","function_tokens":["def","rm_ip","(","ifname",",","dry","=","False",")",":","runner",".","set_dry","(","dry",")","# Remove conf file for network interface (next time the interface could","# have a different number)","netplan_file","=","os",".","path",".","join","(","\"\/etc\/netplan\/\"",",","\"blocksat-\"","+","ifname","+","\".yaml\"",")","net_file","=","os",".","path",".","join","(","\"\/etc\/network\/interfaces.d\/\"",",","ifname","+","\".conf\"",")","ifcfg_file","=","os",".","path",".","join","(","\"\/etc\/sysconfig\/network-scripts\/\"",",","\"ifcfg-\"","+","ifname",")","if","(","which","(","\"netplan\"",")","is","not","None",")",":","cfg_file","=","netplan_file","elif","(","os",".","path",".","exists","(","net_file",")",")",":","cfg_file","=","net_file","elif","(","os",".","path",".","exists","(","ifcfg_file",")",")",":","cfg_file","=","ifcfg_file","else",":","cfg_file","=","None","if","(","cfg_file","is","not","None","and","os",".","path",".","exists","(","cfg_file",")",")",":","runner",".","run","(","[","\"rm\"",",","cfg_file","]",",","root","=","True",")","if","(","not","dry",")",":","logger",".","info","(","\"Removed configuration file {}\"",".","format","(","cfg_file",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L271-L295"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/ip.py","language":"python","identifier":"compute_rx_ips","parameters":"(sat_ip, n_ips, subnet=\"\/29\")","argument_list":"","return_statement":"return ips","docstring":"Compute Rx IPs within the same subnet as the satellite Tx\n\n Args:\n sat_ip : satellite IP in CIDR notation\n n_ips : Request number of IPs\n\n Returns:\n ips list of IPs","docstring_summary":"Compute Rx IPs within the same subnet as the satellite Tx","docstring_tokens":["Compute","Rx","IPs","within","the","same","subnet","as","the","satellite","Tx"],"function":"def compute_rx_ips(sat_ip, n_ips, subnet=\"\/29\"):\n \"\"\"Compute Rx IPs within the same subnet as the satellite Tx\n\n Args:\n sat_ip : satellite IP in CIDR notation\n n_ips : Request number of IPs\n\n Returns:\n ips list of IPs\n\n \"\"\"\n sat_ip_split = [x for x in sat_ip.split(\".\")]\n assert (len(sat_ip_split) == 4)\n base_ip = \".\".join(sat_ip_split[0:3])\n sat_ip_term = int(sat_ip[-1])\n base_offset = 3 # 3 reserved IPs for Tx host and modulator\n assert (n_ips < 5) # 5 IPs remaining for user equipment\n ips = list()\n for i in range(0, n_ips):\n rx_ip_term = sat_ip_term + base_offset + i\n ips.append(base_ip + \".\" + str(rx_ip_term) + subnet)\n return ips","function_tokens":["def","compute_rx_ips","(","sat_ip",",","n_ips",",","subnet","=","\"\/29\"",")",":","sat_ip_split","=","[","x","for","x","in","sat_ip",".","split","(","\".\"",")","]","assert","(","len","(","sat_ip_split",")","==","4",")","base_ip","=","\".\"",".","join","(","sat_ip_split","[","0",":","3","]",")","sat_ip_term","=","int","(","sat_ip","[","-","1","]",")","base_offset","=","3","# 3 reserved IPs for Tx host and modulator","assert","(","n_ips","<","5",")","# 5 IPs remaining for user equipment","ips","=","list","(",")","for","i","in","range","(","0",",","n_ips",")",":","rx_ip_term","=","sat_ip_term","+","base_offset","+","i","ips",".","append","(","base_ip","+","\".\"","+","str","(","rx_ip_term",")","+","subnet",")","return","ips"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/ip.py#L298-L319"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock.__init__","parameters":"(self, sock_addr, ifname, mcast_rx=True)","argument_list":"","return_statement":"","docstring":"Instantiate UDP socket\n\n Args:\n sock_addr : Socket address string\n ifname : Network interface name\n mcast_rx : Use socket to receive multicast packets.\n\n Returns:\n Socket object","docstring_summary":"Instantiate UDP socket","docstring_tokens":["Instantiate","UDP","socket"],"function":"def __init__(self, sock_addr, ifname, mcast_rx=True):\n \"\"\"Instantiate UDP socket\n\n Args:\n sock_addr : Socket address string\n ifname : Network interface name\n mcast_rx : Use socket to receive multicast packets.\n\n Returns:\n Socket object\n\n \"\"\"\n assert (\":\" in sock_addr), \"Socket address must be in ip:port format\"\n self.ip = sock_addr.split(\":\")[0]\n assert (ipaddress.ip_address(self.ip)) # parse address\n self.port = int(sock_addr.split(\":\")[1])\n self.ifindex = None\n\n assert (self.ip is not None), \"UDP source IP is not defined\"\n assert (self.port is not None), \"UDP port is not defined\"\n logger.debug(\"Connect with UDP socket %s:%s\" % (self.ip, self.port))\n\n try:\n # Open and bind socket to Blocksat API port\n self.sock = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n # Allow reuse and bind\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', self.port))\n\n # Get the network interface index\n self._get_ifindex(ifname)\n\n # Join multicast group if listening\n if (mcast_rx):\n self._join_mcast_group()\n\n except socket.error as e:\n if (e.errno == errno.EADDRNOTAVAIL):\n logger.error(\"Error on connection with UDP socket %s:%s\" %\n (self.ip, self.port))\n logger.info(\n \"Use argument `--sock-addr` to define the socket address.\")\n raise","function_tokens":["def","__init__","(","self",",","sock_addr",",","ifname",",","mcast_rx","=","True",")",":","assert","(","\":\"","in","sock_addr",")",",","\"Socket address must be in ip:port format\"","self",".","ip","=","sock_addr",".","split","(","\":\"",")","[","0","]","assert","(","ipaddress",".","ip_address","(","self",".","ip",")",")","# parse address","self",".","port","=","int","(","sock_addr",".","split","(","\":\"",")","[","1","]",")","self",".","ifindex","=","None","assert","(","self",".","ip","is","not","None",")",",","\"UDP source IP is not defined\"","assert","(","self",".","port","is","not","None",")",",","\"UDP port is not defined\"","logger",".","debug","(","\"Connect with UDP socket %s:%s\"","%","(","self",".","ip",",","self",".","port",")",")","try",":","# Open and bind socket to Blocksat API port","self",".","sock","=","sock","=","socket",".","socket","(","socket",".","AF_INET",",","socket",".","SOCK_DGRAM",")","# Allow reuse and bind","sock",".","setsockopt","(","socket",".","SOL_SOCKET",",","socket",".","SO_REUSEADDR",",","1",")","sock",".","bind","(","(","''",",","self",".","port",")",")","# Get the network interface index","self",".","_get_ifindex","(","ifname",")","# Join multicast group if listening","if","(","mcast_rx",")",":","self",".","_join_mcast_group","(",")","except","socket",".","error","as","e",":","if","(","e",".","errno","==","errno",".","EADDRNOTAVAIL",")",":","logger",".","error","(","\"Error on connection with UDP socket %s:%s\"","%","(","self",".","ip",",","self",".","port",")",")","logger",".","info","(","\"Use argument `--sock-addr` to define the socket address.\"",")","raise"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L16-L59"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock.__del__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Destructor","docstring_summary":"Destructor","docstring_tokens":["Destructor"],"function":"def __del__(self):\n \"\"\"Destructor\"\"\"\n if hasattr(self, 'sock'):\n self.sock.close()","function_tokens":["def","__del__","(","self",")",":","if","hasattr","(","self",",","'sock'",")",":","self",".","sock",".","close","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L61-L64"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock._get_ifindex","parameters":"(self, ifname)","argument_list":"","return_statement":"","docstring":"Get the index of a given interface name","docstring_summary":"Get the index of a given interface name","docstring_tokens":["Get","the","index","of","a","given","interface","name"],"function":"def _get_ifindex(self, ifname):\n \"\"\"Get the index of a given interface name\"\"\"\n if (ifname is not None):\n ifreq = struct.pack('16si', ifname.encode(), 0)\n res = fcntl.ioctl(self.sock.fileno(), SIOCGIFINDEX, ifreq)\n self.ifindex = int(struct.unpack('16si', res)[1])\n else:\n self.ifindex = 0","function_tokens":["def","_get_ifindex","(","self",",","ifname",")",":","if","(","ifname","is","not","None",")",":","ifreq","=","struct",".","pack","(","'16si'",",","ifname",".","encode","(",")",",","0",")","res","=","fcntl",".","ioctl","(","self",".","sock",".","fileno","(",")",",","SIOCGIFINDEX",",","ifreq",")","self",".","ifindex","=","int","(","struct",".","unpack","(","'16si'",",","res",")","[","1","]",")","else",":","self",".","ifindex","=","0"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L66-L73"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock._join_mcast_group","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Join multicast group on the chosen interface","docstring_summary":"Join multicast group on the chosen interface","docstring_tokens":["Join","multicast","group","on","the","chosen","interface"],"function":"def _join_mcast_group(self):\n \"\"\"Join multicast group on the chosen interface\"\"\"\n if (self.ifindex != 0):\n logger.debug(\"Join multicast group %s on network interface %d\" %\n (self.ip, self.ifindex))\n else:\n logger.debug(\"Join group %s with the default network interface\" %\n (self.ip))\n\n ip_mreqn = struct.pack('4s4si', socket.inet_aton(self.ip),\n socket.inet_aton('0.0.0.0'), self.ifindex)\n self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,\n ip_mreqn)\n\n # Make sure that this socket receives messages solely from the above\n # group that was explicitly joined above\n self.sock.setsockopt(socket.IPPROTO_IP, IP_MULTICAST_ALL, 0)","function_tokens":["def","_join_mcast_group","(","self",")",":","if","(","self",".","ifindex","!=","0",")",":","logger",".","debug","(","\"Join multicast group %s on network interface %d\"","%","(","self",".","ip",",","self",".","ifindex",")",")","else",":","logger",".","debug","(","\"Join group %s with the default network interface\"","%","(","self",".","ip",")",")","ip_mreqn","=","struct",".","pack","(","'4s4si'",",","socket",".","inet_aton","(","self",".","ip",")",",","socket",".","inet_aton","(","'0.0.0.0'",")",",","self",".","ifindex",")","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","socket",".","IP_ADD_MEMBERSHIP",",","ip_mreqn",")","# Make sure that this socket receives messages solely from the above","# group that was explicitly joined above","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","IP_MULTICAST_ALL",",","0",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L75-L91"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock.set_mcast_tx_opts","parameters":"(self, ttl=1, dscp=0)","argument_list":"","return_statement":"","docstring":"Set options used for transmission of multicast-addressed packets\n\n Args:\n ttl : Time-to-live\n dscp : Differentiated services code point (DSCP)","docstring_summary":"Set options used for transmission of multicast-addressed packets","docstring_tokens":["Set","options","used","for","transmission","of","multicast","-","addressed","packets"],"function":"def set_mcast_tx_opts(self, ttl=1, dscp=0):\n \"\"\"Set options used for transmission of multicast-addressed packets\n\n Args:\n ttl : Time-to-live\n dscp : Differentiated services code point (DSCP)\n\n \"\"\"\n # Define the interface over which to send the multicast messages\n ip_mreqn = struct.pack('4s4si', socket.inet_aton(self.ip),\n socket.inet_aton('0.0.0.0'), self.ifindex)\n self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,\n ip_mreqn)\n\n # Set multicast TTL\n self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,\n struct.pack('b', ttl))\n\n # Set DSCP\n self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS,\n struct.pack('b', dscp))\n\n # Don't loop Tx messages back to us\n self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)","function_tokens":["def","set_mcast_tx_opts","(","self",",","ttl","=","1",",","dscp","=","0",")",":","# Define the interface over which to send the multicast messages","ip_mreqn","=","struct",".","pack","(","'4s4si'",",","socket",".","inet_aton","(","self",".","ip",")",",","socket",".","inet_aton","(","'0.0.0.0'",")",",","self",".","ifindex",")","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","socket",".","IP_MULTICAST_IF",",","ip_mreqn",")","# Set multicast TTL","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","socket",".","IP_MULTICAST_TTL",",","struct",".","pack","(","'b'",",","ttl",")",")","# Set DSCP","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","socket",".","IP_TOS",",","struct",".","pack","(","'b'",",","dscp",")",")","# Don't loop Tx messages back to us","self",".","sock",".","setsockopt","(","socket",".","IPPROTO_IP",",","socket",".","IP_MULTICAST_LOOP",",","0",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L93-L116"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock.send","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Transmit UDP packet\n\n Args:\n data : data to transmit over the UDP payload","docstring_summary":"Transmit UDP packet","docstring_tokens":["Transmit","UDP","packet"],"function":"def send(self, data):\n \"\"\"Transmit UDP packet\n\n Args:\n data : data to transmit over the UDP payload\n\n \"\"\"\n self.sock.sendto(data, (self.ip, self.port))","function_tokens":["def","send","(","self",",","data",")",":","self",".","sock",".","sendto","(","data",",","(","self",".","ip",",","self",".","port",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L118-L125"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/net.py","language":"python","identifier":"UdpSock.recv","parameters":"(self)","argument_list":"","return_statement":"return self.sock.recvfrom(MAX_READ)","docstring":"Blocking receive\n\n Returns:\n Received data.","docstring_summary":"Blocking receive","docstring_tokens":["Blocking","receive"],"function":"def recv(self):\n \"\"\"Blocking receive\n\n Returns:\n Received data.\n\n \"\"\"\n return self.sock.recvfrom(MAX_READ)","function_tokens":["def","recv","(","self",")",":","return","self",".","sock",".","recvfrom","(","MAX_READ",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/net.py#L127-L134"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"generate","parameters":"(data,\n filename=None,\n plaintext=True,\n encapsulate=False,\n sign=False,\n fec=False,\n gpg=None,\n recipient=None,\n trust=False,\n sign_key=None,\n fec_overhead=0.1)","argument_list":"","return_statement":"return msg","docstring":"Generate an API message\n\n Args:\n data : Message data (bytes)\n filename : Underlying file name if the message consists of a file.\n plaintext : Boolean indicating plaintext mode.\n encapsulate : Boolean indicating whether to encapsulate the data.\n sign : Boolean indicating whether the message should be signed.\n fec : Boolean indicating whether to enable FEC encoding.\n gpg : Gpg object.\n recipient : Public key fingerprint of the desired recipient.\n trust : Skip key validation on encryption (trust the recipient).\n sign_key : Fingerprint to use for signing.\n fec_overhead : Target FEC overhead.\n\n Returns:\n Message as an ApiMsg object.","docstring_summary":"Generate an API message","docstring_tokens":["Generate","an","API","message"],"function":"def generate(data,\n filename=None,\n plaintext=True,\n encapsulate=False,\n sign=False,\n fec=False,\n gpg=None,\n recipient=None,\n trust=False,\n sign_key=None,\n fec_overhead=0.1):\n \"\"\"Generate an API message\n\n Args:\n data : Message data (bytes)\n filename : Underlying file name if the message consists of a file.\n plaintext : Boolean indicating plaintext mode.\n encapsulate : Boolean indicating whether to encapsulate the data.\n sign : Boolean indicating whether the message should be signed.\n fec : Boolean indicating whether to enable FEC encoding.\n gpg : Gpg object.\n recipient : Public key fingerprint of the desired recipient.\n trust : Skip key validation on encryption (trust the recipient).\n sign_key : Fingerprint to use for signing.\n fec_overhead : Target FEC overhead.\n\n Returns:\n Message as an ApiMsg object.\n\n \"\"\"\n if ((not plaintext or sign) and gpg is None):\n raise ValueError(\"Gpg object is required for encryption or signing\")\n\n msg = ApiMsg(data, filename=filename)\n\n # If transmitting a plaintext message, it could still be clearsigned.\n if (plaintext and sign):\n if (sign_key):\n # Make sure the key exists\n gpg.get_priv_key(sign_key)\n sign_key = sign_key\n else:\n sign_key = gpg.get_default_priv_key()[\"fingerprint\"]\n\n msg.clearsign(gpg, sign_key)\n\n # Pack data into structure (header + data), if enabled\n if (encapsulate):\n msg.encapsulate()\n\n # Encrypt, unless configured otherwise\n if (not plaintext):\n # Default to the first public key in the keyring if the recipient is\n # not defined.\n if (recipient is None):\n recipient = gpg.get_default_public_key()[\"fingerprint\"]\n assert(recipient != defs.blocksat_pubkey), \\\n \"Defaul public key is not the user's public key\"\n else:\n # Make sure the key exists\n gpg.get_public_key(recipient)\n recipient = recipient\n\n # Digital signature. If configured to sign the message without a\n # specified key, use the default key.\n if (sign):\n if (sign_key):\n # Make sure the key exists\n gpg.get_priv_key(sign_key)\n sign_cfg = sign_key\n else:\n sign_cfg = gpg.get_default_priv_key()[\"fingerprint\"]\n else:\n sign_cfg = False\n\n msg.encrypt(gpg, recipient, sign_cfg, trust)\n\n # Forward error correction encoding\n if (fec):\n msg.fec_encode(fec_overhead)\n\n return msg","function_tokens":["def","generate","(","data",",","filename","=","None",",","plaintext","=","True",",","encapsulate","=","False",",","sign","=","False",",","fec","=","False",",","gpg","=","None",",","recipient","=","None",",","trust","=","False",",","sign_key","=","None",",","fec_overhead","=","0.1",")",":","if","(","(","not","plaintext","or","sign",")","and","gpg","is","None",")",":","raise","ValueError","(","\"Gpg object is required for encryption or signing\"",")","msg","=","ApiMsg","(","data",",","filename","=","filename",")","# If transmitting a plaintext message, it could still be clearsigned.","if","(","plaintext","and","sign",")",":","if","(","sign_key",")",":","# Make sure the key exists","gpg",".","get_priv_key","(","sign_key",")","sign_key","=","sign_key","else",":","sign_key","=","gpg",".","get_default_priv_key","(",")","[","\"fingerprint\"","]","msg",".","clearsign","(","gpg",",","sign_key",")","# Pack data into structure (header + data), if enabled","if","(","encapsulate",")",":","msg",".","encapsulate","(",")","# Encrypt, unless configured otherwise","if","(","not","plaintext",")",":","# Default to the first public key in the keyring if the recipient is","# not defined.","if","(","recipient","is","None",")",":","recipient","=","gpg",".","get_default_public_key","(",")","[","\"fingerprint\"","]","assert","(","recipient","!=","defs",".","blocksat_pubkey",")",",","\"Defaul public key is not the user's public key\"","else",":","# Make sure the key exists","gpg",".","get_public_key","(","recipient",")","recipient","=","recipient","# Digital signature. If configured to sign the message without a","# specified key, use the default key.","if","(","sign",")",":","if","(","sign_key",")",":","# Make sure the key exists","gpg",".","get_priv_key","(","sign_key",")","sign_cfg","=","sign_key","else",":","sign_cfg","=","gpg",".","get_default_priv_key","(",")","[","\"fingerprint\"","]","else",":","sign_cfg","=","False","msg",".","encrypt","(","gpg",",","recipient",",","sign_cfg",",","trust",")","# Forward error correction encoding","if","(","fec",")",":","msg",".","fec_encode","(","fec_overhead",")","return","msg"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L504-L585"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"decode","parameters":"(data,\n plaintext=True,\n decapsulate=False,\n fec=False,\n sender=None,\n gpg=None)","argument_list":"","return_statement":"return msg","docstring":"Decode an incoming API message\n\n Args:\n data : Message data (bytes)\n plaintext : Boolean indicating plaintext mode.\n decapsulate : Boolean indicating whether to encapsulate the data.\n fec : Boolean indicating whether to try FEC decoding first.\n sender : Fingerprint of a sender who must have signed the message.\n gpg : Gpg object.\n\n Returns:\n ApiMsg if the message is succesfully decoded, None otherwise.","docstring_summary":"Decode an incoming API message","docstring_tokens":["Decode","an","incoming","API","message"],"function":"def decode(data,\n plaintext=True,\n decapsulate=False,\n fec=False,\n sender=None,\n gpg=None):\n \"\"\"Decode an incoming API message\n\n Args:\n data : Message data (bytes)\n plaintext : Boolean indicating plaintext mode.\n decapsulate : Boolean indicating whether to encapsulate the data.\n fec : Boolean indicating whether to try FEC decoding first.\n sender : Fingerprint of a sender who must have signed the message.\n gpg : Gpg object.\n\n Returns:\n ApiMsg if the message is succesfully decoded, None otherwise.\n\n \"\"\"\n if ((not plaintext or sender) and gpg is None):\n raise ValueError(\"Gpg object is required for decryption\/verification\")\n\n if (fec):\n msg = ApiMsg(data, msg_format=\"fec_encoded\")\n msg.fec_decode()\n data = msg.data['original']\n del msg # after extracting the data, re-create a new ApiMsg below\n\n if (plaintext):\n if (decapsulate):\n # Encapsulated format, but no encryption\n msg = ApiMsg(data, msg_format=\"encapsulated\")\n\n # Try to decapsulate it\n if (not msg.decapsulate()):\n return\n else:\n # Assume that the message is not encapsulated. This mode is\n # useful, e.g., for compatibility with transmissions triggered\n # from the browser at: https:\/\/blockstream.com\/satellite-queue\/.\n msg = ApiMsg(data, msg_format=\"original\")\n\n # If filtering clearsigned messages, verify\n if (sender and not msg.verify(gpg, sender)):\n return\n\n logger.info(\"Message Size: {:d} bytes\\tSaving in plaintext\".format(\n msg.get_length(target='original')))\n\n else:\n # Cast data into ApiMsg object in encrypted form\n msg = ApiMsg(data, msg_format=\"encrypted\")\n\n # Try to decrypt the data:\n if (not msg.decrypt(gpg, sender)):\n return\n\n # Try to decapsulate the application-layer structure if assuming it\n # is present (i.e., with \"save-raw=False\")\n if (decapsulate and not msg.decapsulate()):\n return\n\n return msg","function_tokens":["def","decode","(","data",",","plaintext","=","True",",","decapsulate","=","False",",","fec","=","False",",","sender","=","None",",","gpg","=","None",")",":","if","(","(","not","plaintext","or","sender",")","and","gpg","is","None",")",":","raise","ValueError","(","\"Gpg object is required for decryption\/verification\"",")","if","(","fec",")",":","msg","=","ApiMsg","(","data",",","msg_format","=","\"fec_encoded\"",")","msg",".","fec_decode","(",")","data","=","msg",".","data","[","'original'","]","del","msg","# after extracting the data, re-create a new ApiMsg below","if","(","plaintext",")",":","if","(","decapsulate",")",":","# Encapsulated format, but no encryption","msg","=","ApiMsg","(","data",",","msg_format","=","\"encapsulated\"",")","# Try to decapsulate it","if","(","not","msg",".","decapsulate","(",")",")",":","return","else",":","# Assume that the message is not encapsulated. This mode is","# useful, e.g., for compatibility with transmissions triggered","# from the browser at: https:\/\/blockstream.com\/satellite-queue\/.","msg","=","ApiMsg","(","data",",","msg_format","=","\"original\"",")","# If filtering clearsigned messages, verify","if","(","sender","and","not","msg",".","verify","(","gpg",",","sender",")",")",":","return","logger",".","info","(","\"Message Size: {:d} bytes\\tSaving in plaintext\"",".","format","(","msg",".","get_length","(","target","=","'original'",")",")",")","else",":","# Cast data into ApiMsg object in encrypted form","msg","=","ApiMsg","(","data",",","msg_format","=","\"encrypted\"",")","# Try to decrypt the data:","if","(","not","msg",".","decrypt","(","gpg",",","sender",")",")",":","return","# Try to decapsulate the application-layer structure if assuming it","# is present (i.e., with \"save-raw=False\")","if","(","decapsulate","and","not","msg",".","decapsulate","(",")",")",":","return","return","msg"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L588-L651"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.__init__","parameters":"(self, data, msg_format=\"original\", filename=None)","argument_list":"","return_statement":"","docstring":"ApiMsg Constructor\n\n Args:\n data : bytes array with the data to send through an API\n message.\n msg_format : message format corresponding to the input data array.\n It could be the original data (\"original\"), the\n encapsulated version of the original data\n (\"encapsulated\"), the encrypted version (\"encrypted\"),\n or the FEC-encoded format (\"fec_encoded\").\n filename : Name of the file represented by the input data, when\n the data corresponds to a file.","docstring_summary":"ApiMsg Constructor","docstring_tokens":["ApiMsg","Constructor"],"function":"def __init__(self, data, msg_format=\"original\", filename=None):\n \"\"\"ApiMsg Constructor\n\n Args:\n data : bytes array with the data to send through an API\n message.\n msg_format : message format corresponding to the input data array.\n It could be the original data (\"original\"), the\n encapsulated version of the original data\n (\"encapsulated\"), the encrypted version (\"encrypted\"),\n or the FEC-encoded format (\"fec_encoded\").\n filename : Name of the file represented by the input data, when\n the data corresponds to a file.\n \"\"\"\n assert (isinstance(data, bytes))\n assert (msg_format in data_formats), \"Unknown message format\"\n\n # Data containers\n self.data = {\n 'original': None, # Original data, before encapsulation\n 'encapsulated': None, # After encapsulation\n 'encrypted': None, # After encryption\n 'fec_encoded': None # After forward error correction\n }\n\n # The input data fills one of the containers:\n self.data[msg_format] = data\n logger.debug(\"{} message has {:d} bytes\".format(\n msg_format.replace(\"_\", \" \").title(), len(data)))\n\n # When the file name is empty, use a timestamp:\n self.filename = filename if filename is not None else \\\n time.strftime(\"%Y%m%d%H%M%S\")\n if (filename is not None):\n logger.debug(\"File name: {}\".format(filename))","function_tokens":["def","__init__","(","self",",","data",",","msg_format","=","\"original\"",",","filename","=","None",")",":","assert","(","isinstance","(","data",",","bytes",")",")","assert","(","msg_format","in","data_formats",")",",","\"Unknown message format\"","# Data containers","self",".","data","=","{","'original'",":","None",",","# Original data, before encapsulation","'encapsulated'",":","None",",","# After encapsulation","'encrypted'",":","None",",","# After encryption","'fec_encoded'",":","None","# After forward error correction","}","# The input data fills one of the containers:","self",".","data","[","msg_format","]","=","data","logger",".","debug","(","\"{} message has {:d} bytes\"",".","format","(","msg_format",".","replace","(","\"_\"",",","\" \"",")",".","title","(",")",",","len","(","data",")",")",")","# When the file name is empty, use a timestamp:","self",".","filename","=","filename","if","filename","is","not","None","else","time",".","strftime","(","\"%Y%m%d%H%M%S\"",")","if","(","filename","is","not","None",")",":","logger",".","debug","(","\"File name: {}\"",".","format","(","filename",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L35-L69"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.get_data","parameters":"(self, target=None)","argument_list":"","return_statement":"","docstring":"Return message data\n\n Returns the data corresponding to the highest data container level\n available, in order of complexity (by convention, fec_encoded >\n encrypted > encapsulated > raw original format). If the target data\n container is specified, return the corresponding data directly.\n\n Args:\n target : Target data container (original, encapsulated, encrypted,\n or fec_encoded).","docstring_summary":"Return message data","docstring_tokens":["Return","message","data"],"function":"def get_data(self, target=None):\n \"\"\"Return message data\n\n Returns the data corresponding to the highest data container level\n available, in order of complexity (by convention, fec_encoded >\n encrypted > encapsulated > raw original format). If the target data\n container is specified, return the corresponding data directly.\n\n Args:\n target : Target data container (original, encapsulated, encrypted,\n or fec_encoded).\n\n \"\"\"\n if target is not None:\n assert (target in data_formats), \"Unknown target container\"\n return self.data[target]\n\n # Take the highest-level container\n if self.data['fec_encoded'] is not None:\n return self.data['fec_encoded']\n elif self.data['encrypted'] is not None:\n return self.data['encrypted']\n elif self.data['encapsulated'] is not None:\n return self.data['encapsulated']\n else:\n return self.data['original']","function_tokens":["def","get_data","(","self",",","target","=","None",")",":","if","target","is","not","None",":","assert","(","target","in","data_formats",")",",","\"Unknown target container\"","return","self",".","data","[","target","]","# Take the highest-level container","if","self",".","data","[","'fec_encoded'","]","is","not","None",":","return","self",".","data","[","'fec_encoded'","]","elif","self",".","data","[","'encrypted'","]","is","not","None",":","return","self",".","data","[","'encrypted'","]","elif","self",".","data","[","'encapsulated'","]","is","not","None",":","return","self",".","data","[","'encapsulated'","]","else",":","return","self",".","data","[","'original'","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L71-L96"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.get_length","parameters":"(self, target=None)","argument_list":"","return_statement":"return len(self.get_data(target))","docstring":"Return the message length\n\n Returns the length corresponding to the highest data container level\n available. If the target data container is specified, return the\n corresponding data.\n\n Args:\n target : Target data container (original, encapsulated, encrypted,\n or fec_encoded).","docstring_summary":"Return the message length","docstring_tokens":["Return","the","message","length"],"function":"def get_length(self, target=None):\n \"\"\"Return the message length\n\n Returns the length corresponding to the highest data container level\n available. If the target data container is specified, return the\n corresponding data.\n\n Args:\n target : Target data container (original, encapsulated, encrypted,\n or fec_encoded).\n\n \"\"\"\n return len(self.get_data(target))","function_tokens":["def","get_length","(","self",",","target","=","None",")",":","return","len","(","self",".","get_data","(","target",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L98-L110"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.encapsulate","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Encapsulate the original data\n\n Add a header to the data including a CRC32 checksum and the file name.","docstring_summary":"Encapsulate the original data","docstring_tokens":["Encapsulate","the","original","data"],"function":"def encapsulate(self):\n \"\"\"Encapsulate the original data\n\n Add a header to the data including a CRC32 checksum and the file name.\n\n \"\"\"\n orig_data = self.data[\"original\"]\n crc32 = zlib.crc32(orig_data)\n header = struct.pack(MSG_HEADER_FORMAT, self.filename.encode(), crc32)\n\n self.data['encapsulated'] = header + orig_data\n\n logger.debug(\"Checksum: {:d}\".format(crc32))\n logger.debug(\"Packed in data structure with a total of %d bytes\" %\n (len(self.data['encapsulated'])))","function_tokens":["def","encapsulate","(","self",")",":","orig_data","=","self",".","data","[","\"original\"","]","crc32","=","zlib",".","crc32","(","orig_data",")","header","=","struct",".","pack","(","MSG_HEADER_FORMAT",",","self",".","filename",".","encode","(",")",",","crc32",")","self",".","data","[","'encapsulated'","]","=","header","+","orig_data","logger",".","debug","(","\"Checksum: {:d}\"",".","format","(","crc32",")",")","logger",".","debug","(","\"Packed in data structure with a total of %d bytes\"","%","(","len","(","self",".","data","[","'encapsulated'","]",")",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L112-L126"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.decapsulate","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Decapsulate the data structure\n\n Unpacks the CRC32 checksum and the file name out of the header. Then,\n validates the data integrity using the checksum.\n\n Returns:\n Boolean indicating whether the parsing was successful","docstring_summary":"Decapsulate the data structure","docstring_tokens":["Decapsulate","the","data","structure"],"function":"def decapsulate(self):\n \"\"\"Decapsulate the data structure\n\n Unpacks the CRC32 checksum and the file name out of the header. Then,\n validates the data integrity using the checksum.\n\n Returns:\n Boolean indicating whether the parsing was successful\n\n \"\"\"\n assert (self.data['encapsulated'] is not None)\n encap_data = self.data['encapsulated']\n\n if (len(encap_data) < MSG_HEADER_LEN):\n logger.error(\"Trying to decapsulate a non-encapsulated message\")\n return False\n\n # Parse the header\n header = struct.unpack(MSG_HEADER_FORMAT, encap_data[:MSG_HEADER_LEN])\n try:\n self.filename = header[0].rstrip(b'\\0').decode()\n except UnicodeDecodeError:\n logger.error(\"Could not parse file name. This is likely a \"\n \"non-encapsulated message.\")\n return False\n in_checksum = header[1]\n\n # Check the integrity of the payload\n payload = encap_data[MSG_HEADER_LEN:]\n calc_checksum = zlib.crc32(payload)\n\n if (calc_checksum != in_checksum):\n logger.error(\"Checksum (%d) does not match the header value (%d)\" %\n (calc_checksum, in_checksum))\n return False\n else:\n logger.info(\"File: %s\\tChecksum: %d\\tSize: %d bytes\" %\n (self.filename, in_checksum, len(payload)))\n\n self.data['original'] = payload\n return True","function_tokens":["def","decapsulate","(","self",")",":","assert","(","self",".","data","[","'encapsulated'","]","is","not","None",")","encap_data","=","self",".","data","[","'encapsulated'","]","if","(","len","(","encap_data",")","<","MSG_HEADER_LEN",")",":","logger",".","error","(","\"Trying to decapsulate a non-encapsulated message\"",")","return","False","# Parse the header","header","=","struct",".","unpack","(","MSG_HEADER_FORMAT",",","encap_data","[",":","MSG_HEADER_LEN","]",")","try",":","self",".","filename","=","header","[","0","]",".","rstrip","(","b'\\0'",")",".","decode","(",")","except","UnicodeDecodeError",":","logger",".","error","(","\"Could not parse file name. This is likely a \"","\"non-encapsulated message.\"",")","return","False","in_checksum","=","header","[","1","]","# Check the integrity of the payload","payload","=","encap_data","[","MSG_HEADER_LEN",":","]","calc_checksum","=","zlib",".","crc32","(","payload",")","if","(","calc_checksum","!=","in_checksum",")",":","logger",".","error","(","\"Checksum (%d) does not match the header value (%d)\"","%","(","calc_checksum",",","in_checksum",")",")","return","False","else",":","logger",".","info","(","\"File: %s\\tChecksum: %d\\tSize: %d bytes\"","%","(","self",".","filename",",","in_checksum",",","len","(","payload",")",")",")","self",".","data","[","'original'","]","=","payload","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L128-L168"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.encrypt","parameters":"(self, gpg, recipient, sign, trust)","argument_list":"","return_statement":"","docstring":"Encrypt the data\n\n If encapsulated data is available, encrypt that. Otherwise, encrypt the\n original data.\n\n Args:\n gpg : Gpg object.\n recipient : Public key fingerprint of the desired recipient.\n sign : GPG sign parameter: True to sign with the default key,\n False to skip signing, or a fingerprint with the key\n to use for signing.\n trust : Skip key validation.","docstring_summary":"Encrypt the data","docstring_tokens":["Encrypt","the","data"],"function":"def encrypt(self, gpg, recipient, sign, trust):\n \"\"\"Encrypt the data\n\n If encapsulated data is available, encrypt that. Otherwise, encrypt the\n original data.\n\n Args:\n gpg : Gpg object.\n recipient : Public key fingerprint of the desired recipient.\n sign : GPG sign parameter: True to sign with the default key,\n False to skip signing, or a fingerprint with the key\n to use for signing.\n trust : Skip key validation.\n\n\n \"\"\"\n data = self.data['encapsulated'] if self.data['encapsulated'] \\\n else self.data['original']\n\n logger.debug(\"Encrypt for recipient %s\" % (recipient))\n\n if (sign and sign is not True):\n logger.debug(\"Sign message using key %s\" % (sign))\n\n encrypted_obj = gpg.encrypt(data,\n recipient,\n always_trust=trust,\n sign=sign)\n if (not encrypted_obj.ok):\n logger.error(encrypted_obj.stderr)\n raise ValueError(encrypted_obj.status)\n\n self.data['encrypted'] = encrypted_obj.data\n logger.debug(\"Encrypted version of the data structure has %d bytes\" %\n (len(self.data['encrypted'])))","function_tokens":["def","encrypt","(","self",",","gpg",",","recipient",",","sign",",","trust",")",":","data","=","self",".","data","[","'encapsulated'","]","if","self",".","data","[","'encapsulated'","]","else","self",".","data","[","'original'","]","logger",".","debug","(","\"Encrypt for recipient %s\"","%","(","recipient",")",")","if","(","sign","and","sign","is","not","True",")",":","logger",".","debug","(","\"Sign message using key %s\"","%","(","sign",")",")","encrypted_obj","=","gpg",".","encrypt","(","data",",","recipient",",","always_trust","=","trust",",","sign","=","sign",")","if","(","not","encrypted_obj",".","ok",")",":","logger",".","error","(","encrypted_obj",".","stderr",")","raise","ValueError","(","encrypted_obj",".","status",")","self",".","data","[","'encrypted'","]","=","encrypted_obj",".","data","logger",".","debug","(","\"Encrypted version of the data structure has %d bytes\"","%","(","len","(","self",".","data","[","'encrypted'","]",")",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L170-L204"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.decrypt","parameters":"(self, gpg, signer_filter=None)","argument_list":"","return_statement":"return True","docstring":"Decrypt the data\n\n Args:\n gpg : Gpg object.\n signer_filter : Fingerprint of a target signer. If the message is\n not signed by this fingerprint, drop it.\n\n Returns:\n True if the decryption was successful.","docstring_summary":"Decrypt the data","docstring_tokens":["Decrypt","the","data"],"function":"def decrypt(self, gpg, signer_filter=None):\n \"\"\"Decrypt the data\n\n Args:\n gpg : Gpg object.\n signer_filter : Fingerprint of a target signer. If the message is\n not signed by this fingerprint, drop it.\n\n Returns:\n True if the decryption was successful.\n\n \"\"\"\n\n decrypted_data = gpg.decrypt(self.data['encrypted'])\n\n if (not decrypted_data.ok):\n logger.info(\"Size: %7d bytes\\t Decryption: FAILED\\t\" %\n (len(self.data['encrypted'])) +\n \"Not encrypted for us (%s)\" % (decrypted_data.status))\n return False\n\n # Is the message digitally signed?\n if (decrypted_data.fingerprint is not None):\n signed_by = decrypted_data.fingerprint\n verified = decrypted_data.trust_level is not None\n sign_str_short = \"Signed\"\n\n if verified:\n sign_str_long = \\\n \"Signed by %s (verified w\/ trust level: %s)\" % (\n signed_by, decrypted_data.trust_text)\n else:\n sign_str_long = \"Signed by %s (unverified)\" % (signed_by)\n else:\n sign_str_short = \"Unsigned\"\n sign_str_long = \"\"\n signed_by = None\n verified = False\n\n logger.info(\"Encrypted size: %7d bytes\\t Decryption: OK \\t%s\" %\n (len(self.data['encrypted']), sign_str_short))\n\n if (len(sign_str_long) > 0):\n logger.info(sign_str_long)\n\n if (signer_filter is not None):\n if (not signed_by):\n logger.warning(\"Dropping message - not signed\")\n return False\n\n if (signer_filter != signed_by):\n logger.warning(\"Dropping message - not signed by the selected \"\n \"sender\")\n return False\n\n if (decrypted_data.trust_level < decrypted_data.TRUST_FULLY):\n logger.warning(\"Dropping message - signature unverified\")\n return False\n\n logger.info(\"Decrypted size: %7d bytes\" % (len(str(decrypted_data))))\n\n # We can't know whether decrypted data is encapsulated or not. So, for\n # now, put the data into both fields. If the decrypted data is\n # encapsulated, eventually \"decapsulate\" will be called and will\n # overwrite the \"original\" data container.\n self.data['original'] = decrypted_data.data\n self.data['encapsulated'] = decrypted_data.data\n\n return True","function_tokens":["def","decrypt","(","self",",","gpg",",","signer_filter","=","None",")",":","decrypted_data","=","gpg",".","decrypt","(","self",".","data","[","'encrypted'","]",")","if","(","not","decrypted_data",".","ok",")",":","logger",".","info","(","\"Size: %7d bytes\\t Decryption: FAILED\\t\"","%","(","len","(","self",".","data","[","'encrypted'","]",")",")","+","\"Not encrypted for us (%s)\"","%","(","decrypted_data",".","status",")",")","return","False","# Is the message digitally signed?","if","(","decrypted_data",".","fingerprint","is","not","None",")",":","signed_by","=","decrypted_data",".","fingerprint","verified","=","decrypted_data",".","trust_level","is","not","None","sign_str_short","=","\"Signed\"","if","verified",":","sign_str_long","=","\"Signed by %s (verified w\/ trust level: %s)\"","%","(","signed_by",",","decrypted_data",".","trust_text",")","else",":","sign_str_long","=","\"Signed by %s (unverified)\"","%","(","signed_by",")","else",":","sign_str_short","=","\"Unsigned\"","sign_str_long","=","\"\"","signed_by","=","None","verified","=","False","logger",".","info","(","\"Encrypted size: %7d bytes\\t Decryption: OK \\t%s\"","%","(","len","(","self",".","data","[","'encrypted'","]",")",",","sign_str_short",")",")","if","(","len","(","sign_str_long",")",">","0",")",":","logger",".","info","(","sign_str_long",")","if","(","signer_filter","is","not","None",")",":","if","(","not","signed_by",")",":","logger",".","warning","(","\"Dropping message - not signed\"",")","return","False","if","(","signer_filter","!=","signed_by",")",":","logger",".","warning","(","\"Dropping message - not signed by the selected \"","\"sender\"",")","return","False","if","(","decrypted_data",".","trust_level","<","decrypted_data",".","TRUST_FULLY",")",":","logger",".","warning","(","\"Dropping message - signature unverified\"",")","return","False","logger",".","info","(","\"Decrypted size: %7d bytes\"","%","(","len","(","str","(","decrypted_data",")",")",")",")","# We can't know whether decrypted data is encapsulated or not. So, for","# now, put the data into both fields. If the decrypted data is","# encapsulated, eventually \"decapsulate\" will be called and will","# overwrite the \"original\" data container.","self",".","data","[","'original'","]","=","decrypted_data",".","data","self",".","data","[","'encapsulated'","]","=","decrypted_data",".","data","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L206-L274"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.clearsign","parameters":"(self, gpg, sign_key)","argument_list":"","return_statement":"","docstring":"Clearsign the data\n\n Unlike the other methods in this class, this method overwrites the\n original data container. The rationale is that, in this case, the\n actual message to be delivered to the recipient becomes the clearsigned\n one, including the signature.\n\n This method should be used in plaintext mode only. In contrast, in\n encryption mode, the signature should be enabled on the call to method\n \"encrypt\" instead.\n\n Args:\n gpg : Gpg object.\n sign_key : Fingerprint to use for signing. If set to None, try with\n the first private key on the keyring.","docstring_summary":"Clearsign the data","docstring_tokens":["Clearsign","the","data"],"function":"def clearsign(self, gpg, sign_key):\n \"\"\"Clearsign the data\n\n Unlike the other methods in this class, this method overwrites the\n original data container. The rationale is that, in this case, the\n actual message to be delivered to the recipient becomes the clearsigned\n one, including the signature.\n\n This method should be used in plaintext mode only. In contrast, in\n encryption mode, the signature should be enabled on the call to method\n \"encrypt\" instead.\n\n Args:\n gpg : Gpg object.\n sign_key : Fingerprint to use for signing. If set to None, try with\n the first private key on the keyring.\n\n \"\"\"\n data = self.data['original']\n\n logger.debug(\"Sign message using key %s\" % (sign_key))\n\n signed_obj = gpg.sign(data, sign_key)\n\n logger.debug(\"Signed version of the data structure has %d bytes\" %\n (len(signed_obj.data)))\n\n self.data['original'] = signed_obj.data","function_tokens":["def","clearsign","(","self",",","gpg",",","sign_key",")",":","data","=","self",".","data","[","'original'","]","logger",".","debug","(","\"Sign message using key %s\"","%","(","sign_key",")",")","signed_obj","=","gpg",".","sign","(","data",",","sign_key",")","logger",".","debug","(","\"Signed version of the data structure has %d bytes\"","%","(","len","(","signed_obj",".","data",")",")",")","self",".","data","[","'original'","]","=","signed_obj",".","data"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L276-L303"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.verify","parameters":"(self, gpg, signer)","argument_list":"","return_statement":"return True","docstring":"Verify signed (but non-encrypted) message from target signer\n\n Detects whether the clearsigned plaintext messages comes from the\n specified signer. In the positive case, overwrite the \"original\" data\n container with the underlying data, excluding the signature. In other\n words, if the verification is succesful, remove the signature and leave\n the data only.\n\n Args:\n gpg : Gpg object.\n signer : Fingerprint of a target signer.\n\n Returns:\n (bool) Whether the message is signed by the target signer.","docstring_summary":"Verify signed (but non-encrypted) message from target signer","docstring_tokens":["Verify","signed","(","but","non","-","encrypted",")","message","from","target","signer"],"function":"def verify(self, gpg, signer):\n \"\"\"Verify signed (but non-encrypted) message from target signer\n\n Detects whether the clearsigned plaintext messages comes from the\n specified signer. In the positive case, overwrite the \"original\" data\n container with the underlying data, excluding the signature. In other\n words, if the verification is succesful, remove the signature and leave\n the data only.\n\n Args:\n gpg : Gpg object.\n signer : Fingerprint of a target signer.\n\n Returns:\n (bool) Whether the message is signed by the target signer.\n\n \"\"\"\n assert (signer is not None)\n\n verif_obj = gpg.gpg.verify(self.data['original'])\n verified = verif_obj.trust_level is not None\n signed_by = verif_obj.fingerprint\n\n if (not signed_by):\n logger.info(\"Dropping message - not signed\")\n return False\n\n if (signed_by != signer):\n logger.info(\"Dropping message - not signed by the selected \"\n \"sender\")\n return False\n\n if (not verified):\n logger.info(\"Dropping message - signature unverified\")\n return False\n\n logger.info(\"Signed by {} (verified w\/ trust level: {})\".format(\n signed_by, verif_obj.trust_text))\n\n if (verif_obj.trust_level < verif_obj.TRUST_FULLY):\n logger.warning(\"Dropping message - signature unverified\")\n return False\n\n # The signature has been verified. However, verif_obj does not return\n # the original data. In this case, gpg.decrypt() can be used to get the\n # original data, even though this is not strictly a decryption. In this\n # case, decrypted_data.ok returns false, but the data becomes available\n # on decrypted_data.data (although with a '\\n' in the end).\n decrypted_data = gpg.decrypt(self.data['original'])\n assert (verif_obj.fingerprint == decrypted_data.fingerprint)\n assert (verif_obj.trust_level == decrypted_data.trust_level)\n assert (decrypted_data.data[-1] == ord('\\n'))\n self.data['original'] = decrypted_data.data[:-1]\n\n return True","function_tokens":["def","verify","(","self",",","gpg",",","signer",")",":","assert","(","signer","is","not","None",")","verif_obj","=","gpg",".","gpg",".","verify","(","self",".","data","[","'original'","]",")","verified","=","verif_obj",".","trust_level","is","not","None","signed_by","=","verif_obj",".","fingerprint","if","(","not","signed_by",")",":","logger",".","info","(","\"Dropping message - not signed\"",")","return","False","if","(","signed_by","!=","signer",")",":","logger",".","info","(","\"Dropping message - not signed by the selected \"","\"sender\"",")","return","False","if","(","not","verified",")",":","logger",".","info","(","\"Dropping message - signature unverified\"",")","return","False","logger",".","info","(","\"Signed by {} (verified w\/ trust level: {})\"",".","format","(","signed_by",",","verif_obj",".","trust_text",")",")","if","(","verif_obj",".","trust_level","<","verif_obj",".","TRUST_FULLY",")",":","logger",".","warning","(","\"Dropping message - signature unverified\"",")","return","False","# The signature has been verified. However, verif_obj does not return","# the original data. In this case, gpg.decrypt() can be used to get the","# original data, even though this is not strictly a decryption. In this","# case, decrypted_data.ok returns false, but the data becomes available","# on decrypted_data.data (although with a '\\n' in the end).","decrypted_data","=","gpg",".","decrypt","(","self",".","data","[","'original'","]",")","assert","(","verif_obj",".","fingerprint","==","decrypted_data",".","fingerprint",")","assert","(","verif_obj",".","trust_level","==","decrypted_data",".","trust_level",")","assert","(","decrypted_data",".","data","[","-","1","]","==","ord","(","'\\n'",")",")","self",".","data","[","'original'","]","=","decrypted_data",".","data","[",":","-","1","]","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L305-L359"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.fec_encode","parameters":"(self, overhead=0.1)","argument_list":"","return_statement":"","docstring":"Forward error correction (FEC) encoding\n\n Adds overhead through FEC encoding so that the message has\n redundancy. With that, the receiver can recover the original message\n even if parts of it are missing. The amount of data that can be missing\n depends on the number of overhead FEC chunks. The latter, in turn, is\n controlled by the overhead parameter.\n\n This function applies FEC encoding to the highest data container level\n available. Furthermore, it generates FEC chunks that completely fill\n the maximum Blocksat Packet payload. All chunks are of equal size and\n the last chunk is padded if necessary.\n\n Args:\n overhead : Percentage of the FEC chunks to add as overhead\n (rounded up).","docstring_summary":"Forward error correction (FEC) encoding","docstring_tokens":["Forward","error","correction","(","FEC",")","encoding"],"function":"def fec_encode(self, overhead=0.1):\n \"\"\"Forward error correction (FEC) encoding\n\n Adds overhead through FEC encoding so that the message has\n redundancy. With that, the receiver can recover the original message\n even if parts of it are missing. The amount of data that can be missing\n depends on the number of overhead FEC chunks. The latter, in turn, is\n controlled by the overhead parameter.\n\n This function applies FEC encoding to the highest data container level\n available. Furthermore, it generates FEC chunks that completely fill\n the maximum Blocksat Packet payload. All chunks are of equal size and\n the last chunk is padded if necessary.\n\n Args:\n overhead : Percentage of the FEC chunks to add as overhead\n (rounded up).\n\n \"\"\"\n fec = Fec(overhead)\n self.data['fec_encoded'] = fec.encode(self.get_data())","function_tokens":["def","fec_encode","(","self",",","overhead","=","0.1",")",":","fec","=","Fec","(","overhead",")","self",".","data","[","'fec_encoded'","]","=","fec",".","encode","(","self",".","get_data","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L361-L381"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.fec_decode","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Forward error correction (FEC) decoding\n\n Try to decode the FEC-encoded message held in the internal container,\n which may be missing some parts of the original FEC-encoded message.\n\n Note:\n This function should be called only when the FEC-encoded object is\n decodable. Otherwise, it throws a RuntimeError exception. Use the\n \"is_fec_decodable()\" method before calling it.","docstring_summary":"Forward error correction (FEC) decoding","docstring_tokens":["Forward","error","correction","(","FEC",")","decoding"],"function":"def fec_decode(self):\n \"\"\"Forward error correction (FEC) decoding\n\n Try to decode the FEC-encoded message held in the internal container,\n which may be missing some parts of the original FEC-encoded message.\n\n Note:\n This function should be called only when the FEC-encoded object is\n decodable. Otherwise, it throws a RuntimeError exception. Use the\n \"is_fec_decodable()\" method before calling it.\n\n \"\"\"\n assert (self.data['fec_encoded'] is not None)\n\n fec = Fec()\n decoded_data = fec.decode(self.data['fec_encoded'])\n\n # The encoded data should be decodable at this point\n if (not decoded_data):\n raise RuntimeError(\"Failed to decode the FEC-encoded message\")\n\n # We can't know whether the underlying message is encrypted or\n # encapsulated. Thus, for now, put the data into all fields. These\n # fields can be overwritten by calling \"decrypt()\" or \"decapsulate()\".\n self.data['original'] = decoded_data\n self.data['encapsulated'] = decoded_data\n self.data['encrypted'] = decoded_data","function_tokens":["def","fec_decode","(","self",")",":","assert","(","self",".","data","[","'fec_encoded'","]","is","not","None",")","fec","=","Fec","(",")","decoded_data","=","fec",".","decode","(","self",".","data","[","'fec_encoded'","]",")","# The encoded data should be decodable at this point","if","(","not","decoded_data",")",":","raise","RuntimeError","(","\"Failed to decode the FEC-encoded message\"",")","# We can't know whether the underlying message is encrypted or","# encapsulated. Thus, for now, put the data into all fields. These","# fields can be overwritten by calling \"decrypt()\" or \"decapsulate()\".","self",".","data","[","'original'","]","=","decoded_data","self",".","data","[","'encapsulated'","]","=","decoded_data","self",".","data","[","'encrypted'","]","=","decoded_data"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L383-L409"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.is_fec_decodable","parameters":"(self)","argument_list":"","return_statement":"return res is not False","docstring":"Check if the FEC-encoded data is decodable\n\n Returns:\n (bool) Whether the FEC-encoded data is decodable.","docstring_summary":"Check if the FEC-encoded data is decodable","docstring_tokens":["Check","if","the","FEC","-","encoded","data","is","decodable"],"function":"def is_fec_decodable(self):\n \"\"\"Check if the FEC-encoded data is decodable\n\n Returns:\n (bool) Whether the FEC-encoded data is decodable.\n\n \"\"\"\n assert (self.data['fec_encoded'] is not None)\n\n fec = Fec()\n res = fec.decode(self.data['fec_encoded'])\n return res is not False","function_tokens":["def","is_fec_decodable","(","self",")",":","assert","(","self",".","data","[","'fec_encoded'","]","is","not","None",")","fec","=","Fec","(",")","res","=","fec",".","decode","(","self",".","data","[","'fec_encoded'","]",")","return","res","is","not","False"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L411-L422"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.save","parameters":"(self, dst_dir, target='original')","argument_list":"","return_statement":"return dst_file","docstring":"Save data into a file\n\n Save the data of a specified container into a file. Name the file\n according to the filename attribute of this class.\n\n If another file with the same name and different contents already\n exists in the download directory, save the data on a new file with an\n appended number (e.g., \"-2\", \"-3\", and so on). Meanwhile, if a file\n with the same name exists and its contents are also the same as the\n incoming data, do not proceed with the saving.\n\n Args:\n dst_dir : Destination directory to save the file\n target : Target bytes array to save (original, encapsulated or\n encrypted).\n\n Returns:\n Path to the downloaded file. If the file already exists, return the\n path to the pre-existing file regardless.","docstring_summary":"Save data into a file","docstring_tokens":["Save","data","into","a","file"],"function":"def save(self, dst_dir, target='original'):\n \"\"\"Save data into a file\n\n Save the data of a specified container into a file. Name the file\n according to the filename attribute of this class.\n\n If another file with the same name and different contents already\n exists in the download directory, save the data on a new file with an\n appended number (e.g., \"-2\", \"-3\", and so on). Meanwhile, if a file\n with the same name exists and its contents are also the same as the\n incoming data, do not proceed with the saving.\n\n Args:\n dst_dir : Destination directory to save the file\n target : Target bytes array to save (original, encapsulated or\n encrypted).\n\n Returns:\n Path to the downloaded file. If the file already exists, return the\n path to the pre-existing file regardless.\n\n \"\"\"\n data = self.get_data(target)\n assert (isinstance(data, bytes))\n\n # Save file into a specific directory\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n\n # If the file already exists, check if it has the same contents as the\n # data array to be saved. Return in the positive case (no need to save\n # it again).\n dst_file = os.path.join(dst_dir, self.filename)\n\n if os.path.exists(dst_file):\n # sha256 hash of the existing file\n with open(dst_file, \"rb\") as fd:\n existing_hash = hashlib.sha256(fd.read()).hexdigest()\n\n # sha256 hash of the incoming data\n incoming_hash = hashlib.sha256(data).hexdigest()\n\n if (incoming_hash == existing_hash):\n logger.info(\"File {} already exists.\".format(dst_file))\n return dst_file\n\n # At this point, if a file with the same name already exists, it can be\n # implied that it has different contents. Hence, save the incoming data\n # with the same name but an appended number.\n filename, ext = os.path.splitext(self.filename)\n i_file = 1\n while (True):\n if not os.path.exists(dst_file):\n break\n i_file += 1\n dst_file = os.path.join(dst_dir,\n filename + \"-\" + str(i_file) + ext)\n\n # Write file with user data\n f = open(dst_file, 'wb')\n f.write(data)\n f.close()\n\n logger.info(\"Saved at {}.\".format(dst_file))\n return dst_file","function_tokens":["def","save","(","self",",","dst_dir",",","target","=","'original'",")",":","data","=","self",".","get_data","(","target",")","assert","(","isinstance","(","data",",","bytes",")",")","# Save file into a specific directory","if","not","os",".","path",".","exists","(","dst_dir",")",":","os",".","makedirs","(","dst_dir",")","# If the file already exists, check if it has the same contents as the","# data array to be saved. Return in the positive case (no need to save","# it again).","dst_file","=","os",".","path",".","join","(","dst_dir",",","self",".","filename",")","if","os",".","path",".","exists","(","dst_file",")",":","# sha256 hash of the existing file","with","open","(","dst_file",",","\"rb\"",")","as","fd",":","existing_hash","=","hashlib",".","sha256","(","fd",".","read","(",")",")",".","hexdigest","(",")","# sha256 hash of the incoming data","incoming_hash","=","hashlib",".","sha256","(","data",")",".","hexdigest","(",")","if","(","incoming_hash","==","existing_hash",")",":","logger",".","info","(","\"File {} already exists.\"",".","format","(","dst_file",")",")","return","dst_file","# At this point, if a file with the same name already exists, it can be","# implied that it has different contents. Hence, save the incoming data","# with the same name but an appended number.","filename",",","ext","=","os",".","path",".","splitext","(","self",".","filename",")","i_file","=","1","while","(","True",")",":","if","not","os",".","path",".","exists","(","dst_file",")",":","break","i_file","+=","1","dst_file","=","os",".","path",".","join","(","dst_dir",",","filename","+","\"-\"","+","str","(","i_file",")","+","ext",")","# Write file with user data","f","=","open","(","dst_file",",","'wb'",")","f",".","write","(","data",")","f",".","close","(",")","logger",".","info","(","\"Saved at {}.\"",".","format","(","dst_file",")",")","return","dst_file"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L424-L488"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/msg.py","language":"python","identifier":"ApiMsg.serialize","parameters":"(self, target='original')","argument_list":"","return_statement":"","docstring":"Serialize data to stdout\n\n Args:\n target : Target bytes array to print (original, encapsulated or\n encrypted).","docstring_summary":"Serialize data to stdout","docstring_tokens":["Serialize","data","to","stdout"],"function":"def serialize(self, target='original'):\n \"\"\"Serialize data to stdout\n\n Args:\n target : Target bytes array to print (original, encapsulated or\n encrypted).\n\n \"\"\"\n data = self.get_data(target)\n assert (isinstance(data, bytes))\n sys.stdout.buffer.write(data)\n sys.stdout.buffer.flush()","function_tokens":["def","serialize","(","self",",","target","=","'original'",")",":","data","=","self",".","get_data","(","target",")","assert","(","isinstance","(","data",",","bytes",")",")","sys",".","stdout",".","buffer",".","write","(","data",")","sys",".","stdout",".","buffer",".","flush","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/msg.py#L490-L501"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder._print_error","parameters":"(self, error)","argument_list":"","return_statement":"","docstring":"Print error returned by API server","docstring_summary":"Print error returned by API server","docstring_tokens":["Print","error","returned","by","API","server"],"function":"def _print_error(self, error):\n \"\"\"Print error returned by API server\"\"\"\n h = (\"-----------------------------------------\"\n \"-----------------------------\")\n if (isinstance(error, dict)):\n error_str = \"\"\n if (\"title\" in error):\n error_str += error[\"title\"]\n if (\"code\" in error):\n error_str += \" (code: {})\".format(error[\"code\"])\n logger.error(h)\n logger.error(textwrap.fill(error_str))\n if (\"detail\" in error):\n logger.error(textwrap.fill(error[\"detail\"]))\n logger.error(h)\n else:\n logger.error(error)","function_tokens":["def","_print_error","(","self",",","error",")",":","h","=","(","\"-----------------------------------------\"","\"-----------------------------\"",")","if","(","isinstance","(","error",",","dict",")",")",":","error_str","=","\"\"","if","(","\"title\"","in","error",")",":","error_str","+=","error","[","\"title\"","]","if","(","\"code\"","in","error",")",":","error_str","+=","\" (code: {})\"",".","format","(","error","[","\"code\"","]",")","logger",".","error","(","h",")","logger",".","error","(","textwrap",".","fill","(","error_str",")",")","if","(","\"detail\"","in","error",")",":","logger",".","error","(","textwrap",".","fill","(","error","[","\"detail\"","]",")",")","logger",".","error","(","h",")","else",":","logger",".","error","(","error",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L38-L54"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder._print_errors","parameters":"(self, r)","argument_list":"","return_statement":"","docstring":"Print all errors returned on JSON response","docstring_summary":"Print all errors returned on JSON response","docstring_tokens":["Print","all","errors","returned","on","JSON","response"],"function":"def _print_errors(self, r):\n \"\"\"Print all errors returned on JSON response\"\"\"\n try:\n if \"errors\" in r.json():\n for error in r.json()[\"errors\"]:\n self._print_error(error)\n except ValueError:\n logger.error(r.text)","function_tokens":["def","_print_errors","(","self",",","r",")",":","try",":","if","\"errors\"","in","r",".","json","(",")",":","for","error","in","r",".","json","(",")","[","\"errors\"","]",":","self",".","_print_error","(","error",")","except","ValueError",":","logger",".","error","(","r",".","text",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L56-L63"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder._prompt_for_uuid_token","parameters":"(self)","argument_list":"","return_statement":"return uuid, auth_token","docstring":"Ask user to provide the UUID and authentication token","docstring_summary":"Ask user to provide the UUID and authentication token","docstring_tokens":["Ask","user","to","provide","the","UUID","and","authentication","token"],"function":"def _prompt_for_uuid_token(self):\n \"\"\"Ask user to provide the UUID and authentication token\"\"\"\n uuid = input(\"UUID: \") or None\n if (uuid is None):\n raise ValueError(\"Order UUID is required\")\n\n auth_token = input(\"Authentication Token: \") or None\n if (auth_token is None):\n raise ValueError(\"Authentication Token is required\")\n\n return uuid, auth_token","function_tokens":["def","_prompt_for_uuid_token","(","self",")",":","uuid","=","input","(","\"UUID: \"",")","or","None","if","(","uuid","is","None",")",":","raise","ValueError","(","\"Order UUID is required\"",")","auth_token","=","input","(","\"Authentication Token: \"",")","or","None","if","(","auth_token","is","None",")",":","raise","ValueError","(","\"Authentication Token is required\"",")","return","uuid",",","auth_token"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L65-L75"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder._fetch","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Fetch a specific order from the server","docstring_summary":"Fetch a specific order from the server","docstring_tokens":["Fetch","a","specific","order","from","the","server"],"function":"def _fetch(self):\n \"\"\"Fetch a specific order from the server\"\"\"\n assert (self.uuid is not None)\n assert (self.auth_token is not None)\n\n r = requests.get(self.server + '\/order\/' + self.uuid,\n headers={'X-Auth-Token': self.auth_token},\n cert=(self.tls_cert, self.tls_key))\n\n if (r.status_code != requests.codes.ok):\n self._print_errors(r)\n\n r.raise_for_status()\n\n self.order = r.json()\n logger.debug(json.dumps(r.json(), indent=4, sort_keys=True))","function_tokens":["def","_fetch","(","self",")",":","assert","(","self",".","uuid","is","not","None",")","assert","(","self",".","auth_token","is","not","None",")","r","=","requests",".","get","(","self",".","server","+","'\/order\/'","+","self",".","uuid",",","headers","=","{","'X-Auth-Token'",":","self",".","auth_token","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","(","r",".","status_code","!=","requests",".","codes",".","ok",")",":","self",".","_print_errors","(","r",")","r",".","raise_for_status","(",")","self",".","order","=","r",".","json","(",")","logger",".","debug","(","json",".","dumps","(","r",".","json","(",")",",","indent","=","4",",","sort_keys","=","True",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L77-L92"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.get","parameters":"(self, uuid=None, auth_token=None)","argument_list":"","return_statement":"","docstring":"Get the API order information\n\n Args:\n uuid : Order UUID. If not defined, prompt user.\n auth_token : Authentication token. If not defined, prompt user.","docstring_summary":"Get the API order information","docstring_tokens":["Get","the","API","order","information"],"function":"def get(self, uuid=None, auth_token=None):\n \"\"\"Get the API order information\n\n Args:\n uuid : Order UUID. If not defined, prompt user.\n auth_token : Authentication token. If not defined, prompt user.\n\n \"\"\"\n if (uuid is None or auth_token is None):\n uuid, auth_token = self._prompt_for_uuid_token()\n\n self.uuid = uuid\n self.auth_token = auth_token\n self._fetch()","function_tokens":["def","get","(","self",",","uuid","=","None",",","auth_token","=","None",")",":","if","(","uuid","is","None","or","auth_token","is","None",")",":","uuid",",","auth_token","=","self",".","_prompt_for_uuid_token","(",")","self",".","uuid","=","uuid","self",".","auth_token","=","auth_token","self",".","_fetch","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L94-L107"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.send","parameters":"(self, data, bid)","argument_list":"","return_statement":"return res","docstring":"Send the transmission order\n\n Args:\n data : Data as bytes array to broadcast over satellite\n bid : Bid in msats\n\n Returns:\n Dictionary with order metadata","docstring_summary":"Send the transmission order","docstring_tokens":["Send","the","transmission","order"],"function":"def send(self, data, bid):\n \"\"\"Send the transmission order\n\n Args:\n data : Data as bytes array to broadcast over satellite\n bid : Bid in msats\n\n Returns:\n Dictionary with order metadata\n\n \"\"\"\n assert (isinstance(data, bytes))\n\n # Post request to the API\n r = requests.post(self.server + '\/order',\n data={'bid': bid},\n files={'file': data},\n cert=(self.tls_cert, self.tls_key))\n\n # In case of failure, check the API error message\n if (r.status_code != requests.codes.ok\n and r.headers['content-type'] == \"application\/json\"):\n self._print_errors(r)\n\n # Raise error if response status indicates failure\n r.raise_for_status()\n\n # Save the UUID and authentication token from the response\n res = r.json()\n self.uuid = res['uuid']\n self.auth_token = res['auth_token']\n\n # Print the response\n logger.debug(\"API Response:\")\n logger.debug(json.dumps(res, indent=4, sort_keys=True))\n\n logger.info(\"Data successfully queued for transmission\\n\")\n print(\"--\\nUUID:\\n%s\" % (res[\"uuid\"]))\n print(\"--\\nAuthentication Token:\\n%s\" % (res[\"auth_token\"]))\n\n if (\"lightning_invoice\" in res):\n print(\"--\\nAmount Due:\\n%s millisatoshis\\n\" %\n (res[\"lightning_invoice\"][\"msatoshi\"]))\n print(\"--\\nLightning Invoice Number:\\n%s\" %\n (res[\"lightning_invoice\"][\"payreq\"]))\n\n return res","function_tokens":["def","send","(","self",",","data",",","bid",")",":","assert","(","isinstance","(","data",",","bytes",")",")","# Post request to the API","r","=","requests",".","post","(","self",".","server","+","'\/order'",",","data","=","{","'bid'",":","bid","}",",","files","=","{","'file'",":","data","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","# In case of failure, check the API error message","if","(","r",".","status_code","!=","requests",".","codes",".","ok","and","r",".","headers","[","'content-type'","]","==","\"application\/json\"",")",":","self",".","_print_errors","(","r",")","# Raise error if response status indicates failure","r",".","raise_for_status","(",")","# Save the UUID and authentication token from the response","res","=","r",".","json","(",")","self",".","uuid","=","res","[","'uuid'","]","self",".","auth_token","=","res","[","'auth_token'","]","# Print the response","logger",".","debug","(","\"API Response:\"",")","logger",".","debug","(","json",".","dumps","(","res",",","indent","=","4",",","sort_keys","=","True",")",")","logger",".","info","(","\"Data successfully queued for transmission\\n\"",")","print","(","\"--\\nUUID:\\n%s\"","%","(","res","[","\"uuid\"","]",")",")","print","(","\"--\\nAuthentication Token:\\n%s\"","%","(","res","[","\"auth_token\"","]",")",")","if","(","\"lightning_invoice\"","in","res",")",":","print","(","\"--\\nAmount Due:\\n%s millisatoshis\\n\"","%","(","res","[","\"lightning_invoice\"","]","[","\"msatoshi\"","]",")",")","print","(","\"--\\nLightning Invoice Number:\\n%s\"","%","(","res","[","\"lightning_invoice\"","]","[","\"payreq\"","]",")",")","return","res"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L109-L155"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.get_data","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get data content sent over an API order","docstring_summary":"Get data content sent over an API order","docstring_tokens":["Get","data","content","sent","over","an","API","order"],"function":"def get_data(self):\n \"\"\"Get data content sent over an API order\"\"\"\n logger.debug(\"Fetch message #%s from API\" % (self.seq_num))\n\n r = requests.get(self.server + '\/message\/' + str(self.seq_num),\n cert=(self.tls_cert, self.tls_key))\n\n r.raise_for_status()\n\n if (r.status_code == requests.codes.ok):\n data = r.content\n return data","function_tokens":["def","get_data","(","self",")",":","logger",".","debug","(","\"Fetch message #%s from API\"","%","(","self",".","seq_num",")",")","r","=","requests",".","get","(","self",".","server","+","'\/message\/'","+","str","(","self",".","seq_num",")",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","r",".","raise_for_status","(",")","if","(","r",".","status_code","==","requests",".","codes",".","ok",")",":","data","=","r",".","content","return","data"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L157-L168"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.wait_state","parameters":"(self, target, timeout=120)","argument_list":"","return_statement":"return ('status' in self.order and self.order['status'] in target)","docstring":"Wait until the order achieves a target state (or states)\n\n Args:\n target : String or list of strings with the state(s) to wait\n for. When given as a list, this function waits until any\n of the states is achieved.\n timeout : Timeout in seconds.\n\n Returns:\n (bool) Whether the state was successfully reached.","docstring_summary":"Wait until the order achieves a target state (or states)","docstring_tokens":["Wait","until","the","order","achieves","a","target","state","(","or","states",")"],"function":"def wait_state(self, target, timeout=120):\n \"\"\"Wait until the order achieves a target state (or states)\n\n Args:\n target : String or list of strings with the state(s) to wait\n for. When given as a list, this function waits until any\n of the states is achieved.\n timeout : Timeout in seconds.\n\n Returns:\n (bool) Whether the state was successfully reached.\n\n \"\"\"\n assert (isinstance(target, str) or isinstance(target, list))\n\n state_seen = {\n 'pending': False,\n 'paid': False,\n 'transmitting': False,\n 'sent': False,\n 'received': False,\n 'cancelled': False,\n 'expired': False\n }\n msg = {\n 'pending': \"- Waiting for payment confirmation...\",\n 'paid': \"- Payment confirmed. Ready to launch transmission...\",\n 'transmitting': \"- Order in transmission...\",\n 'sent': \"- Order successfully transmitted\",\n 'received': \"- Reception confirmed by the ground station\",\n 'cancelled': \"- Transmission cancelled\",\n 'expired': \"- Order expired\"\n }\n requires = {\n 'pending': [],\n 'paid': ['pending'],\n 'transmitting': ['pending', 'paid'],\n 'sent': ['pending', 'paid', 'transmitting'],\n 'received': ['pending', 'paid', 'transmitting', 'sent'],\n 'cancelled': ['pending'],\n 'expired': ['pending']\n }\n\n if (not isinstance(target, list)):\n target = [target]\n assert ([state in state_seen.keys() for state in target])\n\n s_time = time.time()\n while (True):\n self._fetch()\n\n if (not state_seen[self.order['status']]):\n state_seen[self.order['status']] = True\n\n # If the status is not polled fast enough, some intermediate\n # states may not be seen. Mark the implied states as observed\n # and print their messages.\n for prereq_state in requires[self.order['status']]:\n if (not state_seen[prereq_state]):\n state_seen[prereq_state] = True\n print(msg[prereq_state])\n\n # Print the current state\n print(msg[self.order['status']])\n\n if (any([state_seen[x] for x in target])):\n break\n\n c_time = time.time()\n if ((c_time - s_time) > timeout):\n print(\"Timeout\")\n break\n\n time.sleep(0.5)\n\n return ('status' in self.order and self.order['status'] in target)","function_tokens":["def","wait_state","(","self",",","target",",","timeout","=","120",")",":","assert","(","isinstance","(","target",",","str",")","or","isinstance","(","target",",","list",")",")","state_seen","=","{","'pending'",":","False",",","'paid'",":","False",",","'transmitting'",":","False",",","'sent'",":","False",",","'received'",":","False",",","'cancelled'",":","False",",","'expired'",":","False","}","msg","=","{","'pending'",":","\"- Waiting for payment confirmation...\"",",","'paid'",":","\"- Payment confirmed. Ready to launch transmission...\"",",","'transmitting'",":","\"- Order in transmission...\"",",","'sent'",":","\"- Order successfully transmitted\"",",","'received'",":","\"- Reception confirmed by the ground station\"",",","'cancelled'",":","\"- Transmission cancelled\"",",","'expired'",":","\"- Order expired\"","}","requires","=","{","'pending'",":","[","]",",","'paid'",":","[","'pending'","]",",","'transmitting'",":","[","'pending'",",","'paid'","]",",","'sent'",":","[","'pending'",",","'paid'",",","'transmitting'","]",",","'received'",":","[","'pending'",",","'paid'",",","'transmitting'",",","'sent'","]",",","'cancelled'",":","[","'pending'","]",",","'expired'",":","[","'pending'","]","}","if","(","not","isinstance","(","target",",","list",")",")",":","target","=","[","target","]","assert","(","[","state","in","state_seen",".","keys","(",")","for","state","in","target","]",")","s_time","=","time",".","time","(",")","while","(","True",")",":","self",".","_fetch","(",")","if","(","not","state_seen","[","self",".","order","[","'status'","]","]",")",":","state_seen","[","self",".","order","[","'status'","]","]","=","True","# If the status is not polled fast enough, some intermediate","# states may not be seen. Mark the implied states as observed","# and print their messages.","for","prereq_state","in","requires","[","self",".","order","[","'status'","]","]",":","if","(","not","state_seen","[","prereq_state","]",")",":","state_seen","[","prereq_state","]","=","True","print","(","msg","[","prereq_state","]",")","# Print the current state","print","(","msg","[","self",".","order","[","'status'","]","]",")","if","(","any","(","[","state_seen","[","x","]","for","x","in","target","]",")",")",":","break","c_time","=","time",".","time","(",")","if","(","(","c_time","-","s_time",")",">","timeout",")",":","print","(","\"Timeout\"",")","break","time",".","sleep","(","0.5",")","return","(","'status'","in","self",".","order","and","self",".","order","[","'status'","]","in","target",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L170-L245"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.confirm_tx","parameters":"(self, regions)","argument_list":"","return_statement":"","docstring":"Confirm transmission of an API message\n\n Args:\n regions : Regions that were covered by the transmission","docstring_summary":"Confirm transmission of an API message","docstring_tokens":["Confirm","transmission","of","an","API","message"],"function":"def confirm_tx(self, regions):\n \"\"\"Confirm transmission of an API message\n\n Args:\n regions : Regions that were covered by the transmission\n\n \"\"\"\n assert (self.seq_num is not None)\n\n if ((regions is None) or (self.tls_cert is None)\n or (self.tls_key is None)):\n return\n\n assert (isinstance(regions, list))\n\n logger.info(\"Confirm transmission of message {} on regions {}\".format(\n self.seq_num, regions))\n\n r = requests.post(self.server + '\/order\/tx\/' + str(self.seq_num),\n data={'regions': json.dumps(regions)},\n cert=(self.tls_cert, self.tls_key))\n\n if not r.ok:\n logger.error(\"Failed to confirm Tx of message {} \"\n \"[status code {}]\".format(self.seq_num,\n r.status_code))\n self._print_errors(r)\n else:\n logger.info(\"Server response: \" + r.json()['message'])","function_tokens":["def","confirm_tx","(","self",",","regions",")",":","assert","(","self",".","seq_num","is","not","None",")","if","(","(","regions","is","None",")","or","(","self",".","tls_cert","is","None",")","or","(","self",".","tls_key","is","None",")",")",":","return","assert","(","isinstance","(","regions",",","list",")",")","logger",".","info","(","\"Confirm transmission of message {} on regions {}\"",".","format","(","self",".","seq_num",",","regions",")",")","r","=","requests",".","post","(","self",".","server","+","'\/order\/tx\/'","+","str","(","self",".","seq_num",")",",","data","=","{","'regions'",":","json",".","dumps","(","regions",")","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","not","r",".","ok",":","logger",".","error","(","\"Failed to confirm Tx of message {} \"","\"[status code {}]\"",".","format","(","self",".","seq_num",",","r",".","status_code",")",")","self",".","_print_errors","(","r",")","else",":","logger",".","info","(","\"Server response: \"","+","r",".","json","(",")","[","'message'","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L247-L275"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.confirm_rx","parameters":"(self, region)","argument_list":"","return_statement":"","docstring":"Confirm reception of an API message\n\n Args:\n region : Coverage region","docstring_summary":"Confirm reception of an API message","docstring_tokens":["Confirm","reception","of","an","API","message"],"function":"def confirm_rx(self, region):\n \"\"\"Confirm reception of an API message\n\n Args:\n region : Coverage region\n\n \"\"\"\n assert (self.seq_num is not None)\n\n if ((region is None) or (self.tls_cert is None)\n or (self.tls_key is None)):\n return\n\n logger.info(\"Confirm reception of API message {} on region {}\".format(\n self.seq_num, region))\n\n r = requests.post(self.server + '\/order\/rx\/' + str(self.seq_num),\n data={'region': region},\n cert=(self.tls_cert, self.tls_key))\n\n if not r.ok:\n logger.error(\"Failed to confirm Rx of message {} \"\n \"[status code {}]\".format(self.seq_num,\n r.status_code))\n self._print_errors(r)\n else:\n logger.info(\"Server response: \" + r.json()['message'])","function_tokens":["def","confirm_rx","(","self",",","region",")",":","assert","(","self",".","seq_num","is","not","None",")","if","(","(","region","is","None",")","or","(","self",".","tls_cert","is","None",")","or","(","self",".","tls_key","is","None",")",")",":","return","logger",".","info","(","\"Confirm reception of API message {} on region {}\"",".","format","(","self",".","seq_num",",","region",")",")","r","=","requests",".","post","(","self",".","server","+","'\/order\/rx\/'","+","str","(","self",".","seq_num",")",",","data","=","{","'region'",":","region","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","not","r",".","ok",":","logger",".","error","(","\"Failed to confirm Rx of message {} \"","\"[status code {}]\"",".","format","(","self",".","seq_num",",","r",".","status_code",")",")","self",".","_print_errors","(","r",")","else",":","logger",".","info","(","\"Server response: \"","+","r",".","json","(",")","[","'message'","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L277-L303"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.bump","parameters":"(self, bid=None)","argument_list":"","return_statement":"return r.json()","docstring":"Bump the order\n\n Args:\n bid : New bid in msats. If not defined, prompt user.\n\n Returns:\n Dictionary with order metadata","docstring_summary":"Bump the order","docstring_tokens":["Bump","the","order"],"function":"def bump(self, bid=None):\n \"\"\"Bump the order\n\n Args:\n bid : New bid in msats. If not defined, prompt user.\n\n Returns:\n Dictionary with order metadata\n\n \"\"\"\n if (not self.order):\n self._fetch()\n\n if (self.order[\"status\"] == \"transmitting\"):\n raise ValueError(\"Cannot bump order - already in transmission\")\n\n if (self.order[\"status\"] == \"sent\"\n or self.order[\"status\"] == \"received\"):\n raise ValueError(\"Cannot bump order - already transmitted\")\n\n if (self.order[\"status\"] == \"cancelled\"\n or self.order[\"status\"] == \"expired\"):\n raise ValueError(\"Order already {}\".format(self.order[\"status\"]))\n\n if (self.order[\"unpaid_bid\"] > 0):\n unpaid_bid_msg = \"(%d msat paid, %d msat unpaid)\" % (\n self.order[\"bid\"], self.order[\"unpaid_bid\"])\n else:\n unpaid_bid_msg = \"\"\n\n previous_bid = self.order[\"bid\"] + self.order[\"unpaid_bid\"]\n tx_len = pkt.calc_ota_msg_len(self.order[\"message_size\"])\n\n logger.info(\"Previous bid was {:d} msat for {:d} bytes {}\".format(\n previous_bid, tx_len, unpaid_bid_msg))\n\n logger.info(\"Paid bid ratio is currently {:.2f} msat\/byte\".format(\n self.order[\"bid_per_byte\"]))\n logger.info(\"Total (paid + unpaid) bid ratio is currently {:.2f} \"\n \"msat\/byte\".format(float(previous_bid) \/ tx_len))\n\n if (bid is None):\n # Ask for new bid\n bid = bidding.ask_bid(tx_len, previous_bid)\n\n assert (isinstance(bid, int))\n\n # Post bump request\n r = requests.post(self.server + '\/order\/' + self.uuid + \"\/bump\",\n data={\n 'bid_increase': bid - previous_bid,\n 'auth_token': self.auth_token\n },\n cert=(self.tls_cert, self.tls_key))\n\n if (r.status_code != requests.codes.ok):\n self._print_errors(r)\n\n r.raise_for_status()\n\n # Print the response\n logger.info(\"Order bumped successfully\\n\")\n\n print(\"--\\nNew Lightning Invoice Number:\\n%s\\n\" %\n (r.json()[\"lightning_invoice\"][\"payreq\"]))\n print(\"--\\nNew Amount Due:\\n%s millisatoshis\\n\" %\n (r.json()[\"lightning_invoice\"][\"msatoshi\"]))\n\n logger.debug(\"API Response:\")\n logger.debug(json.dumps(r.json(), indent=4, sort_keys=True))\n\n return r.json()","function_tokens":["def","bump","(","self",",","bid","=","None",")",":","if","(","not","self",".","order",")",":","self",".","_fetch","(",")","if","(","self",".","order","[","\"status\"","]","==","\"transmitting\"",")",":","raise","ValueError","(","\"Cannot bump order - already in transmission\"",")","if","(","self",".","order","[","\"status\"","]","==","\"sent\"","or","self",".","order","[","\"status\"","]","==","\"received\"",")",":","raise","ValueError","(","\"Cannot bump order - already transmitted\"",")","if","(","self",".","order","[","\"status\"","]","==","\"cancelled\"","or","self",".","order","[","\"status\"","]","==","\"expired\"",")",":","raise","ValueError","(","\"Order already {}\"",".","format","(","self",".","order","[","\"status\"","]",")",")","if","(","self",".","order","[","\"unpaid_bid\"","]",">","0",")",":","unpaid_bid_msg","=","\"(%d msat paid, %d msat unpaid)\"","%","(","self",".","order","[","\"bid\"","]",",","self",".","order","[","\"unpaid_bid\"","]",")","else",":","unpaid_bid_msg","=","\"\"","previous_bid","=","self",".","order","[","\"bid\"","]","+","self",".","order","[","\"unpaid_bid\"","]","tx_len","=","pkt",".","calc_ota_msg_len","(","self",".","order","[","\"message_size\"","]",")","logger",".","info","(","\"Previous bid was {:d} msat for {:d} bytes {}\"",".","format","(","previous_bid",",","tx_len",",","unpaid_bid_msg",")",")","logger",".","info","(","\"Paid bid ratio is currently {:.2f} msat\/byte\"",".","format","(","self",".","order","[","\"bid_per_byte\"","]",")",")","logger",".","info","(","\"Total (paid + unpaid) bid ratio is currently {:.2f} \"","\"msat\/byte\"",".","format","(","float","(","previous_bid",")","\/","tx_len",")",")","if","(","bid","is","None",")",":","# Ask for new bid","bid","=","bidding",".","ask_bid","(","tx_len",",","previous_bid",")","assert","(","isinstance","(","bid",",","int",")",")","# Post bump request","r","=","requests",".","post","(","self",".","server","+","'\/order\/'","+","self",".","uuid","+","\"\/bump\"",",","data","=","{","'bid_increase'",":","bid","-","previous_bid",",","'auth_token'",":","self",".","auth_token","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","(","r",".","status_code","!=","requests",".","codes",".","ok",")",":","self",".","_print_errors","(","r",")","r",".","raise_for_status","(",")","# Print the response","logger",".","info","(","\"Order bumped successfully\\n\"",")","print","(","\"--\\nNew Lightning Invoice Number:\\n%s\\n\"","%","(","r",".","json","(",")","[","\"lightning_invoice\"","]","[","\"payreq\"","]",")",")","print","(","\"--\\nNew Amount Due:\\n%s millisatoshis\\n\"","%","(","r",".","json","(",")","[","\"lightning_invoice\"","]","[","\"msatoshi\"","]",")",")","logger",".","debug","(","\"API Response:\"",")","logger",".","debug","(","json",".","dumps","(","r",".","json","(",")",",","indent","=","4",",","sort_keys","=","True",")",")","return","r",".","json","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L305-L376"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/order.py","language":"python","identifier":"ApiOrder.delete","parameters":"(self)","argument_list":"","return_statement":"return r.json()","docstring":"Delete the order\n\n Returns:\n API response","docstring_summary":"Delete the order","docstring_tokens":["Delete","the","order"],"function":"def delete(self):\n \"\"\"Delete the order\n\n Returns:\n API response\n\n \"\"\"\n if (not self.order):\n self._fetch()\n\n # Post delete request\n r = requests.delete(self.server + '\/order\/' + self.uuid,\n headers={'X-Auth-Token': self.auth_token},\n cert=(self.tls_cert, self.tls_key))\n\n if (r.status_code != requests.codes.ok):\n self._print_errors(r)\n\n r.raise_for_status()\n\n # Print the response\n logger.info(\"Order deleted successfully\")\n\n logger.debug(\"API Response:\")\n logger.debug(json.dumps(r.json(), indent=4, sort_keys=True))\n\n return r.json()","function_tokens":["def","delete","(","self",")",":","if","(","not","self",".","order",")",":","self",".","_fetch","(",")","# Post delete request","r","=","requests",".","delete","(","self",".","server","+","'\/order\/'","+","self",".","uuid",",","headers","=","{","'X-Auth-Token'",":","self",".","auth_token","}",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","if","(","r",".","status_code","!=","requests",".","codes",".","ok",")",":","self",".","_print_errors","(","r",")","r",".","raise_for_status","(",")","# Print the response","logger",".","info","(","\"Order deleted successfully\"",")","logger",".","debug","(","\"API Response:\"",")","logger",".","debug","(","json",".","dumps","(","r",".","json","(",")",",","indent","=","4",",","sort_keys","=","True",")",")","return","r",".","json","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/order.py#L378-L404"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/bidding.py","language":"python","identifier":"suggest_bid","parameters":"(data_size, prev_bid=None)","argument_list":"","return_statement":"return suggested_bid","docstring":"Suggest a valid bid for the given data transmission length\n\n Args:\n data_size : Size of the transmit data in bytes\n prev_bid : Previous bid, if any\n\n Returns:\n Bid in millisatoshis","docstring_summary":"Suggest a valid bid for the given data transmission length","docstring_tokens":["Suggest","a","valid","bid","for","the","given","data","transmission","length"],"function":"def suggest_bid(data_size, prev_bid=None):\n \"\"\"Suggest a valid bid for the given data transmission length\n\n Args:\n data_size : Size of the transmit data in bytes\n prev_bid : Previous bid, if any\n\n Returns:\n Bid in millisatoshis\n\n \"\"\"\n assert (isinstance(data_size, int))\n\n if (prev_bid is not None):\n # Suggest a 5% higher msat\/byte ratio\n suggested_bid = ceil(DEFAULT_BUMP_FACTOR * prev_bid)\n else:\n suggested_bid = max(ceil(data_size * MIN_BID_PER_BYTE), MIN_BID)\n return suggested_bid","function_tokens":["def","suggest_bid","(","data_size",",","prev_bid","=","None",")",":","assert","(","isinstance","(","data_size",",","int",")",")","if","(","prev_bid","is","not","None",")",":","# Suggest a 5% higher msat\/byte ratio","suggested_bid","=","ceil","(","DEFAULT_BUMP_FACTOR","*","prev_bid",")","else",":","suggested_bid","=","max","(","ceil","(","data_size","*","MIN_BID_PER_BYTE",")",",","MIN_BID",")","return","suggested_bid"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/bidding.py#L14-L32"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/bidding.py","language":"python","identifier":"validate_bid","parameters":"(bid, prev_bid=None)","argument_list":"","return_statement":"return True","docstring":"Validate a given bid\n\n Args:\n bid : New bid in msats\n prev_bid : Previous bid in msats, used if bumping\n\n Returns:\n Bool indicating whether the bid is valid.","docstring_summary":"Validate a given bid","docstring_tokens":["Validate","a","given","bid"],"function":"def validate_bid(bid, prev_bid=None):\n \"\"\"Validate a given bid\n\n Args:\n bid : New bid in msats\n prev_bid : Previous bid in msats, used if bumping\n\n Returns:\n Bool indicating whether the bid is valid.\n\n \"\"\"\n if (bid <= 0):\n print(\"Please provide a positive bid in millisatoshis\")\n return False\n\n if (prev_bid is not None and bid <= prev_bid):\n print(\"Please provide a bid higher than the previous bid\")\n return False\n\n if (bid > MAX_BID):\n print(\"Bid too large. Are you sure you want to bid {:.2f} \"\n \"sats (satoshis)?\".format(bid \/ 1e3))\n return False\n\n return True","function_tokens":["def","validate_bid","(","bid",",","prev_bid","=","None",")",":","if","(","bid","<=","0",")",":","print","(","\"Please provide a positive bid in millisatoshis\"",")","return","False","if","(","prev_bid","is","not","None","and","bid","<=","prev_bid",")",":","print","(","\"Please provide a bid higher than the previous bid\"",")","return","False","if","(","bid",">","MAX_BID",")",":","print","(","\"Bid too large. Are you sure you want to bid {:.2f} \"","\"sats (satoshis)?\"",".","format","(","bid","\/","1e3",")",")","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/bidding.py#L35-L59"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/bidding.py","language":"python","identifier":"ask_bid","parameters":"(data_size, prev_bid=None)","argument_list":"","return_statement":"return bid","docstring":"Prompt user for a bid to transmit the given data size\n\n Args:\n data_size : Size of the transmit data in bytes\n prev_bid : Previous bid, if any\n\n Returns:\n Bid in millisatoshis","docstring_summary":"Prompt user for a bid to transmit the given data size","docstring_tokens":["Prompt","user","for","a","bid","to","transmit","the","given","data","size"],"function":"def ask_bid(data_size, prev_bid=None):\n \"\"\"Prompt user for a bid to transmit the given data size\n\n Args:\n data_size : Size of the transmit data in bytes\n prev_bid : Previous bid, if any\n\n Returns:\n Bid in millisatoshis\n\n \"\"\"\n suggested_bid = suggest_bid(data_size, prev_bid)\n\n print(\"\")\n msg = \"Your {}bid to transmit {:d} bytes (in millisatoshis)\".format(\n (\"new total \" if prev_bid is not None else \"\"), data_size)\n\n while (True):\n bid = util.typed_input(msg, default=suggested_bid)\n if (validate_bid(bid, prev_bid)):\n break\n\n if (prev_bid is not None):\n logger.info(\"Bump bid by %d msat to a total of %d msat \"\n \"(%.2f msat\/byte)\" %\n (bid - prev_bid, bid, float(bid) \/ data_size))\n else:\n logger.info(\"Post data with bid of %d millisatoshis \"\n \"(%.2f msat\/byte)\" % (bid, float(bid) \/ data_size))\n\n return bid","function_tokens":["def","ask_bid","(","data_size",",","prev_bid","=","None",")",":","suggested_bid","=","suggest_bid","(","data_size",",","prev_bid",")","print","(","\"\"",")","msg","=","\"Your {}bid to transmit {:d} bytes (in millisatoshis)\"",".","format","(","(","\"new total \"","if","prev_bid","is","not","None","else","\"\"",")",",","data_size",")","while","(","True",")",":","bid","=","util",".","typed_input","(","msg",",","default","=","suggested_bid",")","if","(","validate_bid","(","bid",",","prev_bid",")",")",":","break","if","(","prev_bid","is","not","None",")",":","logger",".","info","(","\"Bump bid by %d msat to a total of %d msat \"","\"(%.2f msat\/byte)\"","%","(","bid","-","prev_bid",",","bid",",","float","(","bid",")","\/","data_size",")",")","else",":","logger",".","info","(","\"Post data with bid of %d millisatoshis \"","\"(%.2f msat\/byte)\"","%","(","bid",",","float","(","bid",")","\/","data_size",")",")","return","bid"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/bidding.py#L62-L92"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/demorx.py","language":"python","identifier":"DemoRx.__init__","parameters":"(self,\n server,\n socks,\n kbps,\n tx_event,\n channel,\n regions=None,\n tls_cert=None,\n tls_key=None)","argument_list":"","return_statement":"","docstring":"DemoRx Constructor\n\n Args:\n server : API server address where the order lives\n socks : Instances of UdpSock over which to send the packets\n kbps : Target bit rate in kbps\n tx_event : SSE event to use as trigger for transmissions\n channel : API channel number\n regions : Regions covered by the transmission (for Tx\n confirmation)\n tls_key : API client key (for Tx confirmation)\n tls_cer : API client certificate (for Tx confirmation)","docstring_summary":"DemoRx Constructor","docstring_tokens":["DemoRx","Constructor"],"function":"def __init__(self,\n server,\n socks,\n kbps,\n tx_event,\n channel,\n regions=None,\n tls_cert=None,\n tls_key=None):\n \"\"\" DemoRx Constructor\n\n Args:\n server : API server address where the order lives\n socks : Instances of UdpSock over which to send the packets\n kbps : Target bit rate in kbps\n tx_event : SSE event to use as trigger for transmissions\n channel : API channel number\n regions : Regions covered by the transmission (for Tx\n confirmation)\n tls_key : API client key (for Tx confirmation)\n tls_cer : API client certificate (for Tx confirmation)\n\n\n \"\"\"\n # Validate args\n assert (isinstance(socks, list))\n assert (all([isinstance(x, net.UdpSock) for x in socks]))\n\n # Configs\n self.server = server\n self.socks = socks\n self.kbps = kbps\n self.tx_event = tx_event\n self.channel = channel\n self.regions = regions\n self.tls_cert = tls_cert\n self.tls_key = tls_key\n\n # State\n self.last_seq_num = None","function_tokens":["def","__init__","(","self",",","server",",","socks",",","kbps",",","tx_event",",","channel",",","regions","=","None",",","tls_cert","=","None",",","tls_key","=","None",")",":","# Validate args","assert","(","isinstance","(","socks",",","list",")",")","assert","(","all","(","[","isinstance","(","x",",","net",".","UdpSock",")","for","x","in","socks","]",")",")","# Configs","self",".","server","=","server","self",".","socks","=","socks","self",".","kbps","=","kbps","self",".","tx_event","=","tx_event","self",".","channel","=","channel","self",".","regions","=","regions","self",".","tls_cert","=","tls_cert","self",".","tls_key","=","tls_key","# State","self",".","last_seq_num","=","None"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/demorx.py#L24-L63"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/demorx.py","language":"python","identifier":"DemoRx._send_pkts","parameters":"(self, pkts)","argument_list":"","return_statement":"","docstring":"Transmit Blocksat packets of the API message over all sockets\n\n Transmit and sleep (i.e., block) to guarantee the target bit rate.\n\n Args:\n pkts : List of BlocksatPkt objects to be send over sockets","docstring_summary":"Transmit Blocksat packets of the API message over all sockets","docstring_tokens":["Transmit","Blocksat","packets","of","the","API","message","over","all","sockets"],"function":"def _send_pkts(self, pkts):\n \"\"\"Transmit Blocksat packets of the API message over all sockets\n\n Transmit and sleep (i.e., block) to guarantee the target bit rate.\n\n Args:\n pkts : List of BlocksatPkt objects to be send over sockets\n\n \"\"\"\n assert (isinstance(pkts, list))\n assert (all([isinstance(x, BlocksatPkt) for x in pkts]))\n\n byte_rate = self.kbps * 1e3 \/ 8 # bytes \/ sec\n next_tx = time.time()\n for i, pkt in enumerate(pkts):\n # Send the same packet on all sockets\n for sock in self.socks:\n sock.send(pkt.pack())\n logger.debug(\"Send packet %d - %d bytes\" % (i, len(pkt)))\n\n # Throttle\n tx_delay = len(pkt) \/ byte_rate\n next_tx += tx_delay\n sleep = next_tx - time.time()\n if (sleep > 0):\n time.sleep(sleep)","function_tokens":["def","_send_pkts","(","self",",","pkts",")",":","assert","(","isinstance","(","pkts",",","list",")",")","assert","(","all","(","[","isinstance","(","x",",","BlocksatPkt",")","for","x","in","pkts","]",")",")","byte_rate","=","self",".","kbps","*","1e3","\/","8","# bytes \/ sec","next_tx","=","time",".","time","(",")","for","i",",","pkt","in","enumerate","(","pkts",")",":","# Send the same packet on all sockets","for","sock","in","self",".","socks",":","sock",".","send","(","pkt",".","pack","(",")",")","logger",".","debug","(","\"Send packet %d - %d bytes\"","%","(","i",",","len","(","pkt",")",")",")","# Throttle","tx_delay","=","len","(","pkt",")","\/","byte_rate","next_tx","+=","tx_delay","sleep","=","next_tx","-","time",".","time","(",")","if","(","sleep",">","0",")",":","time",".","sleep","(","sleep",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/demorx.py#L65-L90"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/demorx.py","language":"python","identifier":"DemoRx._handle_event","parameters":"(self, event)","argument_list":"","return_statement":"","docstring":"Handle event broadcast by the SSE server\n\n Args:\n event : Event generated by the sseclient","docstring_summary":"Handle event broadcast by the SSE server","docstring_tokens":["Handle","event","broadcast","by","the","SSE","server"],"function":"def _handle_event(self, event):\n \"\"\"Handle event broadcast by the SSE server\n\n Args:\n event : Event generated by the sseclient\n\n \"\"\"\n # Parse the order corresponding to the event\n order = json.loads(event.data)\n\n # Debug\n logger.debug(\"Order: \" + json.dumps(order, indent=4, sort_keys=True))\n\n # Proceed when the event matches the target Tx trigger event\n if (order[\"status\"] != self.tx_event):\n return\n\n # Sequence number\n seq_num = order[\"tx_seq_num\"]\n\n # If the sequence number has rolled back, maybe it is because the\n # server has restarted the sequence numbers (not uncommon on test\n # environments). In this case, restart the sequence.\n if (self.last_seq_num is not None and seq_num < self.last_seq_num):\n logger.warning(\"Tx sequence number rolled back from {} to \"\n \"{}\".format(self.last_seq_num, seq_num))\n self.last_seq_num = None\n\n rx_pending = True\n while (rx_pending):\n # Receive all messages until caught up\n if (self.last_seq_num is None):\n next_seq_num = seq_num\n else:\n next_seq_num = self.last_seq_num + 1\n\n # Keep track of the last processed sequence number\n self.last_seq_num = next_seq_num\n\n # Is this an interation to catch up with a sequence\n # number gap or a normal transmission iteration?\n if (seq_num == next_seq_num):\n rx_pending = False\n else:\n logger.info(\"Catch up with transmission %d\" % (next_seq_num))\n\n logger.info(\"Message %-5d\\tSize: %d bytes\\t\" %\n (next_seq_num, order[\"message_size\"]))\n\n # Get the API message data\n order = ApiOrder(self.server,\n seq_num=next_seq_num,\n tls_cert=self.tls_cert,\n tls_key=self.tls_key)\n data = order.get_data()\n\n if (data is None):\n # Empty message. There is nothing else to do.\n continue\n\n # Split API message data into Blocksat packet(s)\n tx_handler = BlocksatPktHandler()\n tx_handler.split(data, next_seq_num, self.channel)\n pkts = tx_handler.get_frags(next_seq_num)\n\n logger.debug(\"Transmission is going to take: \"\n \"{:6.2f} sec\".format(len(data) * 8 \/ (self.kbps)))\n\n # Send the packet(s)\n self._send_pkts(pkts)\n\n # Send transmission confirmation to the server\n order.confirm_tx(self.regions)","function_tokens":["def","_handle_event","(","self",",","event",")",":","# Parse the order corresponding to the event","order","=","json",".","loads","(","event",".","data",")","# Debug","logger",".","debug","(","\"Order: \"","+","json",".","dumps","(","order",",","indent","=","4",",","sort_keys","=","True",")",")","# Proceed when the event matches the target Tx trigger event","if","(","order","[","\"status\"","]","!=","self",".","tx_event",")",":","return","# Sequence number","seq_num","=","order","[","\"tx_seq_num\"","]","# If the sequence number has rolled back, maybe it is because the","# server has restarted the sequence numbers (not uncommon on test","# environments). In this case, restart the sequence.","if","(","self",".","last_seq_num","is","not","None","and","seq_num","<","self",".","last_seq_num",")",":","logger",".","warning","(","\"Tx sequence number rolled back from {} to \"","\"{}\"",".","format","(","self",".","last_seq_num",",","seq_num",")",")","self",".","last_seq_num","=","None","rx_pending","=","True","while","(","rx_pending",")",":","# Receive all messages until caught up","if","(","self",".","last_seq_num","is","None",")",":","next_seq_num","=","seq_num","else",":","next_seq_num","=","self",".","last_seq_num","+","1","# Keep track of the last processed sequence number","self",".","last_seq_num","=","next_seq_num","# Is this an interation to catch up with a sequence","# number gap or a normal transmission iteration?","if","(","seq_num","==","next_seq_num",")",":","rx_pending","=","False","else",":","logger",".","info","(","\"Catch up with transmission %d\"","%","(","next_seq_num",")",")","logger",".","info","(","\"Message %-5d\\tSize: %d bytes\\t\"","%","(","next_seq_num",",","order","[","\"message_size\"","]",")",")","# Get the API message data","order","=","ApiOrder","(","self",".","server",",","seq_num","=","next_seq_num",",","tls_cert","=","self",".","tls_cert",",","tls_key","=","self",".","tls_key",")","data","=","order",".","get_data","(",")","if","(","data","is","None",")",":","# Empty message. There is nothing else to do.","continue","# Split API message data into Blocksat packet(s)","tx_handler","=","BlocksatPktHandler","(",")","tx_handler",".","split","(","data",",","next_seq_num",",","self",".","channel",")","pkts","=","tx_handler",".","get_frags","(","next_seq_num",")","logger",".","debug","(","\"Transmission is going to take: \"","\"{:6.2f} sec\"",".","format","(","len","(","data",")","*","8","\/","(","self",".","kbps",")",")",")","# Send the packet(s)","self",".","_send_pkts","(","pkts",")","# Send transmission confirmation to the server","order",".","confirm_tx","(","self",".","regions",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/demorx.py#L92-L164"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/demorx.py","language":"python","identifier":"DemoRx.run","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Run the demo-rx transmission loop","docstring_summary":"Run the demo-rx transmission loop","docstring_tokens":["Run","the","demo","-","rx","transmission","loop"],"function":"def run(self):\n \"\"\"Run the demo-rx transmission loop\"\"\"\n logger.info(\"Connecting with Satellite API server...\")\n while (True):\n try:\n # Server-sent Events (SSE) Client\n r = requests.get(self.server + \"\/subscribe\/transmissions\",\n stream=True,\n cert=(self.tls_cert, self.tls_key))\n r.raise_for_status()\n client = sseclient.SSEClient(r)\n logger.info(\"Connected. Waiting for events...\\n\")\n\n # Continuously wait for events\n for event in client.events():\n self._handle_event(event)\n\n except requests.exceptions.ChunkedEncodingError as e:\n logger.debug(e)\n pass\n\n except requests.exceptions.ConnectionError as e:\n logger.debug(e)\n time.sleep(2)\n pass\n\n except requests.exceptions.RequestException as e:\n logger.debug(e)\n time.sleep(2)\n pass\n\n except KeyboardInterrupt:\n exit()\n\n logger.info(\"Reconnecting...\")","function_tokens":["def","run","(","self",")",":","logger",".","info","(","\"Connecting with Satellite API server...\"",")","while","(","True",")",":","try",":","# Server-sent Events (SSE) Client","r","=","requests",".","get","(","self",".","server","+","\"\/subscribe\/transmissions\"",",","stream","=","True",",","cert","=","(","self",".","tls_cert",",","self",".","tls_key",")",")","r",".","raise_for_status","(",")","client","=","sseclient",".","SSEClient","(","r",")","logger",".","info","(","\"Connected. Waiting for events...\\n\"",")","# Continuously wait for events","for","event","in","client",".","events","(",")",":","self",".","_handle_event","(","event",")","except","requests",".","exceptions",".","ChunkedEncodingError","as","e",":","logger",".","debug","(","e",")","pass","except","requests",".","exceptions",".","ConnectionError","as","e",":","logger",".","debug","(","e",")","time",".","sleep","(","2",")","pass","except","requests",".","exceptions",".","RequestException","as","e",":","logger",".","debug","(","e",")","time",".","sleep","(","2",")","pass","except","KeyboardInterrupt",":","exit","(",")","logger",".","info","(","\"Reconnecting...\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/demorx.py#L166-L200"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/listen.py","language":"python","identifier":"ApiListener.__init__","parameters":"(self, recv_once=False, recv_queue=None)","argument_list":"","return_statement":"","docstring":"Constructor\n\n Args:\n recv_once : Receive a single message and stop\n recv_queue : Queue to mirror (store) the saved\/serialized messages\n\n Note:\n The constructor options are useful for testing but are not\n necessary in production code.","docstring_summary":"Constructor","docstring_tokens":["Constructor"],"function":"def __init__(self, recv_once=False, recv_queue=None):\n \"\"\"Constructor\n\n Args:\n recv_once : Receive a single message and stop\n recv_queue : Queue to mirror (store) the saved\/serialized messages\n\n Note:\n The constructor options are useful for testing but are not\n necessary in production code.\n\n \"\"\"\n self.enabled = True\n self.recv_once = recv_once\n assert (recv_queue is None or isinstance(recv_queue, queue.Queue))\n self.recv_queue = recv_queue","function_tokens":["def","__init__","(","self",",","recv_once","=","False",",","recv_queue","=","None",")",":","self",".","enabled","=","True","self",".","recv_once","=","recv_once","assert","(","recv_queue","is","None","or","isinstance","(","recv_queue",",","queue",".","Queue",")",")","self",".","recv_queue","=","recv_queue"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/listen.py#L16-L31"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/listen.py","language":"python","identifier":"ApiListener.run","parameters":"(self,\n gpg,\n download_dir,\n sock_addr,\n interface,\n channel,\n plaintext,\n save_raw,\n sender=None,\n stdout=False,\n no_save=False,\n echo=False,\n exec_cmd=None,\n gossip_opts=None,\n server_addr=None,\n tls_cert=None,\n tls_key=None,\n region=None)","argument_list":"","return_statement":"","docstring":"Run loop\n\n Args:\n gpg : Gnupg object\n download_dir : Directory where downloaded messages are saved\n sock_addr : Multicast socket address to listen to\n interface : Network interface to listen to\n channel : Satellite API channel to listen to\n plaintext : Receive messages in plaintext mode\n save_raw : Save the raw message content without decapsulation\n sender : Sender's GPG fingerprint for filtering of messages\n stdout : Print messages to stdout instead of saving them\n no_save : Don't save downloaded messages\n echo : Echo text messages to stdout on reception\n exec_cmd : Arbitrary shell command to run for each download\n gossip_opts : Options for reception of Lightning gossip snapshots\n server_addr : API server address for Rx confirmations\n tls_cert : TLS client cert to authenticate on Rx confirmations\n tls_key : TLS client key to authenticate on Rx confirmations\n region : Satellite region to inform on Rx confirmations","docstring_summary":"Run loop","docstring_tokens":["Run","loop"],"function":"def run(self,\n gpg,\n download_dir,\n sock_addr,\n interface,\n channel,\n plaintext,\n save_raw,\n sender=None,\n stdout=False,\n no_save=False,\n echo=False,\n exec_cmd=None,\n gossip_opts=None,\n server_addr=None,\n tls_cert=None,\n tls_key=None,\n region=None):\n \"\"\"Run loop\n\n Args:\n gpg : Gnupg object\n download_dir : Directory where downloaded messages are saved\n sock_addr : Multicast socket address to listen to\n interface : Network interface to listen to\n channel : Satellite API channel to listen to\n plaintext : Receive messages in plaintext mode\n save_raw : Save the raw message content without decapsulation\n sender : Sender's GPG fingerprint for filtering of messages\n stdout : Print messages to stdout instead of saving them\n no_save : Don't save downloaded messages\n echo : Echo text messages to stdout on reception\n exec_cmd : Arbitrary shell command to run for each download\n gossip_opts : Options for reception of Lightning gossip snapshots\n server_addr : API server address for Rx confirmations\n tls_cert : TLS client cert to authenticate on Rx confirmations\n tls_key : TLS client key to authenticate on Rx confirmations\n region : Satellite region to inform on Rx confirmations\n\n \"\"\"\n logger.debug(\"Starting API listener\")\n\n # Open UDP socket\n sock = net.UdpSock(sock_addr, interface)\n\n # Handler to collect groups of Blocksat packets that form an API\n # message\n pkt_handler = BlocksatPktHandler()\n\n # Set of decoded messages (to avoid repeated decoding)\n decoded_msgs = set()\n\n logger.info(\"Waiting for data...\")\n while self.enabled:\n try:\n udp_payload, addr = sock.recv()\n except KeyboardInterrupt:\n break\n\n # Cast payload to BlocksatPkt object\n pkt = BlocksatPkt()\n pkt.unpack(udp_payload)\n\n # Filter API channel\n if (channel != ApiChannel.ALL.value and pkt.chan_num != channel):\n logger.debug(\"Packet discarded (channel {:d})\".format(\n pkt.chan_num))\n continue\n\n # Feed new packet into the packet handler\n all_frags_received = pkt_handler.append(pkt)\n\n # Decode each message only once\n seq_num = pkt.seq_num\n chan_seq_num = \"{}-{}\".format(pkt.chan_num, seq_num)\n if (chan_seq_num in decoded_msgs):\n logger.debug(\"Message {} from channel {} has already been \"\n \"decoded\".format(seq_num, pkt.chan_num))\n continue\n\n # Assume that the incoming message has forward error correction\n # (FEC) encoding. With FEC, the message may become decodable before\n # receiving all fragments (BlocksatPkts). For every packet, check\n # if the FEC data is decodable already and proceed with the\n # processing in the positive case. If the message is not actually\n # FEC-encoded, it will never assert the \"fec_decodable\" flag. In\n # this case, proceed with the processing only when all fragments\n # are received.\n msg = api_msg.ApiMsg(pkt_handler.concat(seq_num, force=True),\n msg_format=\"fec_encoded\")\n fec_decodable = msg.is_fec_decodable()\n if (not fec_decodable and not all_frags_received):\n continue\n\n # API message is ready to be decoded\n if (channel == ApiChannel.ALL.value):\n logger.info(\"-------- API message {:d} (channel {:d})\".format(\n seq_num, pkt.chan_num))\n else:\n logger.info(\"-------- API message {:d}\".format(seq_num))\n logger.debug(\"Message source: {}:{}\".format(addr[0], addr[1]))\n logger.info(\"Fragments: {:d}\".format(\n pkt_handler.get_n_frags(seq_num)))\n\n # Send confirmation of reception to API server\n order = ApiOrder(server_addr,\n seq_num=seq_num,\n tls_cert=tls_cert,\n tls_key=tls_key)\n order.confirm_rx(region)\n\n # Decode the data from the available FEC chunks or from the\n # complete collection of Blocksat Packets\n if (fec_decodable):\n msg.fec_decode()\n data = msg.data['original']\n else:\n data = pkt_handler.concat(seq_num)\n\n # Mark as decoded\n decoded_msgs.add(chan_seq_num)\n\n # Delete message from the packet handler\n del pkt_handler.frag_map[seq_num]\n\n # Clean up old (timed-out) messages from the packet handler\n pkt_handler.clean()\n\n if (len(data) <= 0):\n logger.warning(\"Empty message\")\n continue\n\n # The FEC-decoded data could be encrypted, signed, and\/or\n # encapsulated. Decode it and obtain the original data.\n msg = api_msg.decode(data,\n plaintext=plaintext,\n decapsulate=(not save_raw),\n sender=sender,\n gpg=gpg)\n if (msg is None):\n continue\n\n # Finalize the processing of the decoded message\n if (stdout):\n msg.serialize()\n elif (not no_save):\n download_path = msg.save(download_dir)\n\n if (self.recv_queue is not None):\n self.recv_queue.put(msg.get_data(target='original'))\n\n if (echo):\n # Not all messages can be decoded in UTF-8 (binary files\n # cannot). Also, messages that were not sent in plaintext and\n # raw (non-encapsulated) format. Echo the results only when the\n # UTF-8 decoding works.\n try:\n logger.info(\"Message:\\n\\n {} \\n\".format(\n msg.data['original'].decode()))\n except UnicodeDecodeError:\n logger.debug(\"Message not decodable in UFT-8\")\n else:\n logger.debug(\"Message: {}\".format(msg.data['original']))\n\n if (exec_cmd):\n cmd = shlex.split(\n exec_cmd.replace(\"{}\", shlex.quote(download_path)))\n logger.debug(\"Exec:\\n> {}\".format(\" \".join(cmd)))\n subprocess.run(cmd)\n\n if (gossip_opts is not None):\n cmd = [\n gossip_opts['cli'], 'snapshot', 'load',\n shlex.quote(download_path)\n ]\n if (gossip_opts['dest'] is not None):\n cmd.append(gossip_opts['dest'])\n\n logger.debug(\"Exec:\\n> {}\".format(\" \".join(cmd)))\n subprocess.run(cmd)\n\n if (self.recv_once):\n self.stop()","function_tokens":["def","run","(","self",",","gpg",",","download_dir",",","sock_addr",",","interface",",","channel",",","plaintext",",","save_raw",",","sender","=","None",",","stdout","=","False",",","no_save","=","False",",","echo","=","False",",","exec_cmd","=","None",",","gossip_opts","=","None",",","server_addr","=","None",",","tls_cert","=","None",",","tls_key","=","None",",","region","=","None",")",":","logger",".","debug","(","\"Starting API listener\"",")","# Open UDP socket","sock","=","net",".","UdpSock","(","sock_addr",",","interface",")","# Handler to collect groups of Blocksat packets that form an API","# message","pkt_handler","=","BlocksatPktHandler","(",")","# Set of decoded messages (to avoid repeated decoding)","decoded_msgs","=","set","(",")","logger",".","info","(","\"Waiting for data...\"",")","while","self",".","enabled",":","try",":","udp_payload",",","addr","=","sock",".","recv","(",")","except","KeyboardInterrupt",":","break","# Cast payload to BlocksatPkt object","pkt","=","BlocksatPkt","(",")","pkt",".","unpack","(","udp_payload",")","# Filter API channel","if","(","channel","!=","ApiChannel",".","ALL",".","value","and","pkt",".","chan_num","!=","channel",")",":","logger",".","debug","(","\"Packet discarded (channel {:d})\"",".","format","(","pkt",".","chan_num",")",")","continue","# Feed new packet into the packet handler","all_frags_received","=","pkt_handler",".","append","(","pkt",")","# Decode each message only once","seq_num","=","pkt",".","seq_num","chan_seq_num","=","\"{}-{}\"",".","format","(","pkt",".","chan_num",",","seq_num",")","if","(","chan_seq_num","in","decoded_msgs",")",":","logger",".","debug","(","\"Message {} from channel {} has already been \"","\"decoded\"",".","format","(","seq_num",",","pkt",".","chan_num",")",")","continue","# Assume that the incoming message has forward error correction","# (FEC) encoding. With FEC, the message may become decodable before","# receiving all fragments (BlocksatPkts). For every packet, check","# if the FEC data is decodable already and proceed with the","# processing in the positive case. If the message is not actually","# FEC-encoded, it will never assert the \"fec_decodable\" flag. In","# this case, proceed with the processing only when all fragments","# are received.","msg","=","api_msg",".","ApiMsg","(","pkt_handler",".","concat","(","seq_num",",","force","=","True",")",",","msg_format","=","\"fec_encoded\"",")","fec_decodable","=","msg",".","is_fec_decodable","(",")","if","(","not","fec_decodable","and","not","all_frags_received",")",":","continue","# API message is ready to be decoded","if","(","channel","==","ApiChannel",".","ALL",".","value",")",":","logger",".","info","(","\"-------- API message {:d} (channel {:d})\"",".","format","(","seq_num",",","pkt",".","chan_num",")",")","else",":","logger",".","info","(","\"-------- API message {:d}\"",".","format","(","seq_num",")",")","logger",".","debug","(","\"Message source: {}:{}\"",".","format","(","addr","[","0","]",",","addr","[","1","]",")",")","logger",".","info","(","\"Fragments: {:d}\"",".","format","(","pkt_handler",".","get_n_frags","(","seq_num",")",")",")","# Send confirmation of reception to API server","order","=","ApiOrder","(","server_addr",",","seq_num","=","seq_num",",","tls_cert","=","tls_cert",",","tls_key","=","tls_key",")","order",".","confirm_rx","(","region",")","# Decode the data from the available FEC chunks or from the","# complete collection of Blocksat Packets","if","(","fec_decodable",")",":","msg",".","fec_decode","(",")","data","=","msg",".","data","[","'original'","]","else",":","data","=","pkt_handler",".","concat","(","seq_num",")","# Mark as decoded","decoded_msgs",".","add","(","chan_seq_num",")","# Delete message from the packet handler","del","pkt_handler",".","frag_map","[","seq_num","]","# Clean up old (timed-out) messages from the packet handler","pkt_handler",".","clean","(",")","if","(","len","(","data",")","<=","0",")",":","logger",".","warning","(","\"Empty message\"",")","continue","# The FEC-decoded data could be encrypted, signed, and\/or","# encapsulated. Decode it and obtain the original data.","msg","=","api_msg",".","decode","(","data",",","plaintext","=","plaintext",",","decapsulate","=","(","not","save_raw",")",",","sender","=","sender",",","gpg","=","gpg",")","if","(","msg","is","None",")",":","continue","# Finalize the processing of the decoded message","if","(","stdout",")",":","msg",".","serialize","(",")","elif","(","not","no_save",")",":","download_path","=","msg",".","save","(","download_dir",")","if","(","self",".","recv_queue","is","not","None",")",":","self",".","recv_queue",".","put","(","msg",".","get_data","(","target","=","'original'",")",")","if","(","echo",")",":","# Not all messages can be decoded in UTF-8 (binary files","# cannot). Also, messages that were not sent in plaintext and","# raw (non-encapsulated) format. Echo the results only when the","# UTF-8 decoding works.","try",":","logger",".","info","(","\"Message:\\n\\n {} \\n\"",".","format","(","msg",".","data","[","'original'","]",".","decode","(",")",")",")","except","UnicodeDecodeError",":","logger",".","debug","(","\"Message not decodable in UFT-8\"",")","else",":","logger",".","debug","(","\"Message: {}\"",".","format","(","msg",".","data","[","'original'","]",")",")","if","(","exec_cmd",")",":","cmd","=","shlex",".","split","(","exec_cmd",".","replace","(","\"{}\"",",","shlex",".","quote","(","download_path",")",")",")","logger",".","debug","(","\"Exec:\\n> {}\"",".","format","(","\" \"",".","join","(","cmd",")",")",")","subprocess",".","run","(","cmd",")","if","(","gossip_opts","is","not","None",")",":","cmd","=","[","gossip_opts","[","'cli'","]",",","'snapshot'",",","'load'",",","shlex",".","quote","(","download_path",")","]","if","(","gossip_opts","[","'dest'","]","is","not","None",")",":","cmd",".","append","(","gossip_opts","[","'dest'","]",")","logger",".","debug","(","\"Exec:\\n> {}\"",".","format","(","\" \"",".","join","(","cmd",")",")",")","subprocess",".","run","(","cmd",")","if","(","self",".","recv_once",")",":","self",".","stop","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/listen.py#L37-L219"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"_is_gpg_keyring_set","parameters":"(gnupghome)","argument_list":"","return_statement":"return True","docstring":"Check if the keyring is already configured\n\n It is configured when:\n - It has at least one private key\n - It has at least two public keys\n - One of the public keys is the blocksat pubkey","docstring_summary":"Check if the keyring is already configured","docstring_tokens":["Check","if","the","keyring","is","already","configured"],"function":"def _is_gpg_keyring_set(gnupghome):\n \"\"\"Check if the keyring is already configured\n\n It is configured when:\n - It has at least one private key\n - It has at least two public keys\n - One of the public keys is the blocksat pubkey\n\n \"\"\"\n if not os.path.exists(gnupghome):\n return False\n\n gpg = Gpg(gnupghome)\n\n if (len(gpg.gpg.list_keys(True)) == 0): # no private key\n return False\n\n if (len(gpg.gpg.list_keys()) < 2): # no two public keys\n return False\n\n if (len(gpg.gpg.list_keys(\n keys=defs.blocksat_pubkey)) == 0): # blocksat key\n return False\n\n return True","function_tokens":["def","_is_gpg_keyring_set","(","gnupghome",")",":","if","not","os",".","path",".","exists","(","gnupghome",")",":","return","False","gpg","=","Gpg","(","gnupghome",")","if","(","len","(","gpg",".","gpg",".","list_keys","(","True",")",")","==","0",")",":","# no private key","return","False","if","(","len","(","gpg",".","gpg",".","list_keys","(",")",")","<","2",")",":","# no two public keys","return","False","if","(","len","(","gpg",".","gpg",".","list_keys","(","keys","=","defs",".","blocksat_pubkey",")",")","==","0",")",":","# blocksat key","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L164-L188"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"config_keyring","parameters":"(gpg, log_if_configured=False)","argument_list":"","return_statement":"","docstring":"Configure the local keyring\n\n Create a keypair and import Blockstream's public key\n\n Args:\n gpg : Gpg object\n log_if_configured : Print log message if keyring is already configured","docstring_summary":"Configure the local keyring","docstring_tokens":["Configure","the","local","keyring"],"function":"def config_keyring(gpg, log_if_configured=False):\n \"\"\"Configure the local keyring\n\n Create a keypair and import Blockstream's public key\n\n Args:\n gpg : Gpg object\n log_if_configured : Print log message if keyring is already configured\n\n \"\"\"\n assert (isinstance(gpg, Gpg))\n if _is_gpg_keyring_set(gpg.gpghome):\n if (log_if_configured):\n logger.info(\"Keyring already configured\")\n return\n\n # Generate new keypair\n logger.info(\"Generating a GPG keypair to encrypt and decrypt API messages\")\n name = input(\"User name represented by the key: \")\n email = input(\"E-mail address: \")\n comment = input(\"Comment to attach to the user ID: \")\n gpg.create_keys(name, email, comment)\n\n # Import Blockstream's public key\n #\n # NOTE: the order is important here. Add Blockstream's public key only\n # after adding the user key. With that, the user key becomes the first key\n # on the keyring, which is used by default.\n pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n key_path = os.path.join(pkg_dir, 'gpg', defs.blocksat_pubkey + \".gpg\")\n\n with open(key_path) as fd:\n key_data = fd.read()\n\n import_result = gpg.gpg.import_keys(key_data)\n\n if (len(import_result.fingerprints) == 0):\n logger.warning(\"Failed to import key {}\".format(defs.blocksat_pubkey))\n return\n\n logger.info(\"Imported key {}\".format(import_result.fingerprints[0]))\n\n gpg.gpg.trust_keys(defs.blocksat_pubkey, 'TRUST_ULTIMATE')\n\n if (not _is_gpg_keyring_set(gpg.gpghome)):\n raise RuntimeError(\"GPG keyring configuration failed\")","function_tokens":["def","config_keyring","(","gpg",",","log_if_configured","=","False",")",":","assert","(","isinstance","(","gpg",",","Gpg",")",")","if","_is_gpg_keyring_set","(","gpg",".","gpghome",")",":","if","(","log_if_configured",")",":","logger",".","info","(","\"Keyring already configured\"",")","return","# Generate new keypair","logger",".","info","(","\"Generating a GPG keypair to encrypt and decrypt API messages\"",")","name","=","input","(","\"User name represented by the key: \"",")","email","=","input","(","\"E-mail address: \"",")","comment","=","input","(","\"Comment to attach to the user ID: \"",")","gpg",".","create_keys","(","name",",","email",",","comment",")","# Import Blockstream's public key","#","# NOTE: the order is important here. Add Blockstream's public key only","# after adding the user key. With that, the user key becomes the first key","# on the keyring, which is used by default.","pkg_dir","=","os",".","path",".","dirname","(","os",".","path",".","dirname","(","os",".","path",".","abspath","(","__file__",")",")",")","key_path","=","os",".","path",".","join","(","pkg_dir",",","'gpg'",",","defs",".","blocksat_pubkey","+","\".gpg\"",")","with","open","(","key_path",")","as","fd",":","key_data","=","fd",".","read","(",")","import_result","=","gpg",".","gpg",".","import_keys","(","key_data",")","if","(","len","(","import_result",".","fingerprints",")","==","0",")",":","logger",".","warning","(","\"Failed to import key {}\"",".","format","(","defs",".","blocksat_pubkey",")",")","return","logger",".","info","(","\"Imported key {}\"",".","format","(","import_result",".","fingerprints","[","0","]",")",")","gpg",".","gpg",".","trust_keys","(","defs",".","blocksat_pubkey",",","'TRUST_ULTIMATE'",")","if","(","not","_is_gpg_keyring_set","(","gpg",".","gpghome",")",")",":","raise","RuntimeError","(","\"GPG keyring configuration failed\"",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L191-L236"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.__init__","parameters":"(self, gpghome, verbose=False, interactive=False)","argument_list":"","return_statement":"","docstring":"Create GnuPG instance","docstring_summary":"Create GnuPG instance","docstring_tokens":["Create","GnuPG","instance"],"function":"def __init__(self, gpghome, verbose=False, interactive=False):\n \"\"\"Create GnuPG instance\"\"\"\n if (not os.path.exists(gpghome)):\n os.mkdir(gpghome)\n # Make sure only the owner has permissions to read, write, and\n # execute the GPG home directory\n os.chmod(gpghome, stat.S_IRWXU)\n\n self.interactive = interactive\n self.gpghome = gpghome\n self.passphrase = None\n\n # Create GPG object and fetch the list of current private keys\n self.gpg = gnupg.GPG(verbose=verbose, gnupghome=gpghome)","function_tokens":["def","__init__","(","self",",","gpghome",",","verbose","=","False",",","interactive","=","False",")",":","if","(","not","os",".","path",".","exists","(","gpghome",")",")",":","os",".","mkdir","(","gpghome",")","# Make sure only the owner has permissions to read, write, and","# execute the GPG home directory","os",".","chmod","(","gpghome",",","stat",".","S_IRWXU",")","self",".","interactive","=","interactive","self",".","gpghome","=","gpghome","self",".","passphrase","=","None","# Create GPG object and fetch the list of current private keys","self",".","gpg","=","gnupg",".","GPG","(","verbose","=","verbose",",","gnupghome","=","gpghome",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L15-L28"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg._find_gpg_key_by_email","parameters":"(self, email)","argument_list":"","return_statement":"","docstring":"Find GPG key with matching email address on UID","docstring_summary":"Find GPG key with matching email address on UID","docstring_tokens":["Find","GPG","key","with","matching","email","address","on","UID"],"function":"def _find_gpg_key_by_email(self, email):\n \"\"\"Find GPG key with matching email address on UID\"\"\"\n\n # Fetch the list of current private keys\n current_priv_keys = self.gpg.list_keys(True)\n\n for key in current_priv_keys:\n for uid in key['uids']:\n if (email in uid):\n return key","function_tokens":["def","_find_gpg_key_by_email","(","self",",","email",")",":","# Fetch the list of current private keys","current_priv_keys","=","self",".","gpg",".","list_keys","(","True",")","for","key","in","current_priv_keys",":","for","uid","in","key","[","'uids'","]",":","if","(","email","in","uid",")",":","return","key"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L30-L39"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.create_keys","parameters":"(self, name, email, comment, passphrase=None)","argument_list":"","return_statement":"","docstring":"Generate GPG Keys","docstring_summary":"Generate GPG Keys","docstring_tokens":["Generate","GPG","Keys"],"function":"def create_keys(self, name, email, comment, passphrase=None):\n \"\"\"Generate GPG Keys\"\"\"\n\n # Check if there is already a key with this e-mail address\n matching_key = self._find_gpg_key_by_email(email)\n if (matching_key):\n logger.info(\"Found existing key {} with uid {}\".format(\n matching_key['fingerprint'], matching_key['uids']))\n\n if (not self.interactive):\n logger.info(\"Aborting\")\n return\n elif (util.ask_yes_or_no(\"Abort the creation of a new key?\")):\n return\n\n # Password\n if (passphrase is None):\n self.prompt_passphrase('Please enter a passphrase to protect '\n 'your key: ')\n else:\n self.set_passphrase(passphrase)\n\n # Generate key\n key_params = self.gpg.gen_key_input(key_type=\"RSA\",\n key_length=1024,\n name_real=name,\n name_comment=comment,\n name_email=email,\n passphrase=self.passphrase)\n self.gpg.gen_key(key_params)\n logger.info(\"Keys succesfully generated at {}\".format(\n os.path.abspath(self.gpghome)))","function_tokens":["def","create_keys","(","self",",","name",",","email",",","comment",",","passphrase","=","None",")",":","# Check if there is already a key with this e-mail address","matching_key","=","self",".","_find_gpg_key_by_email","(","email",")","if","(","matching_key",")",":","logger",".","info","(","\"Found existing key {} with uid {}\"",".","format","(","matching_key","[","'fingerprint'","]",",","matching_key","[","'uids'","]",")",")","if","(","not","self",".","interactive",")",":","logger",".","info","(","\"Aborting\"",")","return","elif","(","util",".","ask_yes_or_no","(","\"Abort the creation of a new key?\"",")",")",":","return","# Password","if","(","passphrase","is","None",")",":","self",".","prompt_passphrase","(","'Please enter a passphrase to protect '","'your key: '",")","else",":","self",".","set_passphrase","(","passphrase",")","# Generate key","key_params","=","self",".","gpg",".","gen_key_input","(","key_type","=","\"RSA\"",",","key_length","=","1024",",","name_real","=","name",",","name_comment","=","comment",",","name_email","=","email",",","passphrase","=","self",".","passphrase",")","self",".","gpg",".","gen_key","(","key_params",")","logger",".","info","(","\"Keys succesfully generated at {}\"",".","format","(","os",".","path",".","abspath","(","self",".","gpghome",")",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L41-L72"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.get_default_public_key","parameters":"(self)","argument_list":"","return_statement":"return self.gpg.list_keys()[0]","docstring":"Get info corresponding to the first public key on the keyring\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.","docstring_summary":"Get info corresponding to the first public key on the keyring","docstring_tokens":["Get","info","corresponding","to","the","first","public","key","on","the","keyring"],"function":"def get_default_public_key(self):\n \"\"\"Get info corresponding to the first public key on the keyring\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.\n\n \"\"\"\n return self.gpg.list_keys()[0]","function_tokens":["def","get_default_public_key","(","self",")",":","return","self",".","gpg",".","list_keys","(",")","[","0","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L87-L95"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.get_default_priv_key","parameters":"(self)","argument_list":"","return_statement":"return self.gpg.list_keys(True)[0]","docstring":"Get info corresponding to the first private key on the keyring\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.","docstring_summary":"Get info corresponding to the first private key on the keyring","docstring_tokens":["Get","info","corresponding","to","the","first","private","key","on","the","keyring"],"function":"def get_default_priv_key(self):\n \"\"\"Get info corresponding to the first private key on the keyring\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.\n\n \"\"\"\n return self.gpg.list_keys(True)[0]","function_tokens":["def","get_default_priv_key","(","self",")",":","return","self",".","gpg",".","list_keys","(","True",")","[","0","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L97-L105"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.get_public_key","parameters":"(self, fingerprint)","argument_list":"","return_statement":"return key_map[fingerprint]","docstring":"Find a specific public key on the keyring and return the info dict\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.","docstring_summary":"Find a specific public key on the keyring and return the info dict","docstring_tokens":["Find","a","specific","public","key","on","the","keyring","and","return","the","info","dict"],"function":"def get_public_key(self, fingerprint):\n \"\"\"Find a specific public key on the keyring and return the info dict\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.\n\n \"\"\"\n key_map = self.gpg.list_keys().key_map\n assert(fingerprint in key_map), \\\n \"Could not find public key {}\".format(fingerprint)\n return key_map[fingerprint]","function_tokens":["def","get_public_key","(","self",",","fingerprint",")",":","key_map","=","self",".","gpg",".","list_keys","(",")",".","key_map","assert","(","fingerprint","in","key_map",")",",","\"Could not find public key {}\"",".","format","(","fingerprint",")","return","key_map","[","fingerprint","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L107-L118"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.get_priv_key","parameters":"(self, fingerprint)","argument_list":"","return_statement":"return key_map[fingerprint]","docstring":"Find a specific private key on the keyring and return the info dict\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.","docstring_summary":"Find a specific private key on the keyring and return the info dict","docstring_tokens":["Find","a","specific","private","key","on","the","keyring","and","return","the","info","dict"],"function":"def get_priv_key(self, fingerprint):\n \"\"\"Find a specific private key on the keyring and return the info dict\n\n Returns:\n Dictionary with key information such as 'fingerprint', 'keyid', and\n 'uids'.\n \"\"\"\n key_map = self.gpg.list_keys(True).key_map\n assert(fingerprint in key_map), \\\n \"Could not find private key {}\".format(fingerprint)\n return key_map[fingerprint]","function_tokens":["def","get_priv_key","(","self",",","fingerprint",")",":","key_map","=","self",".","gpg",".","list_keys","(","True",")",".","key_map","assert","(","fingerprint","in","key_map",")",",","\"Could not find private key {}\"",".","format","(","fingerprint",")","return","key_map","[","fingerprint","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L120-L130"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.encrypt","parameters":"(self, data, recipients, always_trust=False, sign=None)","argument_list":"","return_statement":"return self.gpg.encrypt(data,\n recipients,\n always_trust=always_trust,\n sign=sign,\n passphrase=self.passphrase)","docstring":"Encrypt a given data array","docstring_summary":"Encrypt a given data array","docstring_tokens":["Encrypt","a","given","data","array"],"function":"def encrypt(self, data, recipients, always_trust=False, sign=None):\n \"\"\"Encrypt a given data array\"\"\"\n return self.gpg.encrypt(data,\n recipients,\n always_trust=always_trust,\n sign=sign,\n passphrase=self.passphrase)","function_tokens":["def","encrypt","(","self",",","data",",","recipients",",","always_trust","=","False",",","sign","=","None",")",":","return","self",".","gpg",".","encrypt","(","data",",","recipients",",","always_trust","=","always_trust",",","sign","=","sign",",","passphrase","=","self",".","passphrase",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L132-L138"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.decrypt","parameters":"(self, data)","argument_list":"","return_statement":"return self.gpg.decrypt(data, passphrase=self.passphrase)","docstring":"Decrypt a given data array","docstring_summary":"Decrypt a given data array","docstring_tokens":["Decrypt","a","given","data","array"],"function":"def decrypt(self, data):\n \"\"\"Decrypt a given data array\"\"\"\n if (not self.interactive and self.passphrase is None):\n raise RuntimeError(\n \"Passphrase must be defined in non-interactive mode\")\n\n return self.gpg.decrypt(data, passphrase=self.passphrase)","function_tokens":["def","decrypt","(","self",",","data",")",":","if","(","not","self",".","interactive","and","self",".","passphrase","is","None",")",":","raise","RuntimeError","(","\"Passphrase must be defined in non-interactive mode\"",")","return","self",".","gpg",".","decrypt","(","data",",","passphrase","=","self",".","passphrase",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L140-L146"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/gpg.py","language":"python","identifier":"Gpg.sign","parameters":"(self, data, keyid, clearsign=True, detach=False)","argument_list":"","return_statement":"return self.gpg.sign(data,\n keyid=keyid,\n clearsign=clearsign,\n detach=detach,\n passphrase=self.passphrase)","docstring":"Sign a given data array","docstring_summary":"Sign a given data array","docstring_tokens":["Sign","a","given","data","array"],"function":"def sign(self, data, keyid, clearsign=True, detach=False):\n \"\"\"Sign a given data array\"\"\"\n assert(not (clearsign and detach)), \\\n \"clearsign and detach options are mutually exclusive\"\n\n if (not self.interactive and self.passphrase is None):\n raise RuntimeError(\n \"Passphrase must be defined in non-interactive mode\")\n\n return self.gpg.sign(data,\n keyid=keyid,\n clearsign=clearsign,\n detach=detach,\n passphrase=self.passphrase)","function_tokens":["def","sign","(","self",",","data",",","keyid",",","clearsign","=","True",",","detach","=","False",")",":","assert","(","not","(","clearsign","and","detach",")",")",",","\"clearsign and detach options are mutually exclusive\"","if","(","not","self",".","interactive","and","self",".","passphrase","is","None",")",":","raise","RuntimeError","(","\"Passphrase must be defined in non-interactive mode\"",")","return","self",".","gpg",".","sign","(","data",",","keyid","=","keyid",",","clearsign","=","clearsign",",","detach","=","detach",",","passphrase","=","self",".","passphrase",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/gpg.py#L148-L161"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"_warn_common_overrides","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Warn options overridden by arguments --gossip and --btc-src","docstring_summary":"Warn options overridden by arguments --gossip and --btc-src","docstring_tokens":["Warn","options","overridden","by","arguments","--","gossip","and","--","btc","-","src"],"function":"def _warn_common_overrides(args):\n \"\"\"Warn options overridden by arguments --gossip and --btc-src\"\"\"\n if (not (args.gossip or args.btc_src)):\n return\n\n opt = \"--gossip\" if args.gossip else \"--btc-src\"\n\n if (args.channel != ApiChannel.USER.value):\n logger.warning(\"Option {} overrides --channel\".format(opt))\n\n if (args.server != server_map['main'] or args.net is not None):\n logger.warning(\"Option {} overrides --net and --server\".format(opt))","function_tokens":["def","_warn_common_overrides","(","args",")",":","if","(","not","(","args",".","gossip","or","args",".","btc_src",")",")",":","return","opt","=","\"--gossip\"","if","args",".","gossip","else","\"--btc-src\"","if","(","args",".","channel","!=","ApiChannel",".","USER",".","value",")",":","logger",".","warning","(","\"Option {} overrides --channel\"",".","format","(","opt",")",")","if","(","args",".","server","!=","server_map","[","'main'","]","or","args",".","net","is","not","None",")",":","logger",".","warning","(","\"Option {} overrides --net and --server\"",".","format","(","opt",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L39-L50"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"config","parameters":"(args)","argument_list":"","return_statement":"","docstring":"API config command","docstring_summary":"API config command","docstring_tokens":["API","config","command"],"function":"def config(args):\n \"\"\"API config command\"\"\"\n gnupghome = os.path.join(args.cfg_dir, args.gnupghome)\n gpg = Gpg(gnupghome, verbose=args.verbose, interactive=True)\n config_keyring(gpg, log_if_configured=True)","function_tokens":["def","config","(","args",")",":","gnupghome","=","os",".","path",".","join","(","args",".","cfg_dir",",","args",".","gnupghome",")","gpg","=","Gpg","(","gnupghome",",","verbose","=","args",".","verbose",",","interactive","=","True",")","config_keyring","(","gpg",",","log_if_configured","=","True",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L53-L57"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"send","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Send a message over satellite","docstring_summary":"Send a message over satellite","docstring_tokens":["Send","a","message","over","satellite"],"function":"def send(args):\n \"\"\"Send a message over satellite\"\"\"\n gnupghome = os.path.join(args.cfg_dir, args.gnupghome)\n server_addr = _get_server_addr(args.net, args.server)\n\n # Instantiate the GPG wrapper object if running with encryption or signing\n if (not args.plaintext or args.sign):\n gpg = Gpg(gnupghome, interactive=True)\n config_keyring(gpg)\n else:\n gpg = None\n\n # A passphrase is required if signing\n if (args.sign and (not args.no_password)):\n gpg.prompt_passphrase('Password to private key used for message '\n 'signing: ')\n\n # File or text message to send over satellite\n if (args.file is None):\n if (args.message is None):\n data = input(\"Type a message: \").encode()\n print()\n else:\n data = args.message.encode()\n basename = None\n else:\n basename = os.path.basename(args.file)\n with open(args.file, 'rb') as f:\n data = f.read()\n\n assert(len(data) > 0), \\\n \"Empty {}\".format(\"file\" if args.file else \"message\")\n\n # Put file or text within an API message\n msg = api_msg.generate(data,\n filename=basename,\n plaintext=args.plaintext,\n encapsulate=(not args.send_raw),\n sign=args.sign,\n fec=args.fec,\n gpg=gpg,\n recipient=args.recipient,\n trust=args.trust,\n sign_key=args.sign_key,\n fec_overhead=args.fec_overhead)\n\n # Actual number of bytes used for satellite transmission\n tx_len = calc_ota_msg_len(msg.get_length())\n logger.info(\"Satellite transmission will use %d bytes\" % (tx_len))\n\n # Ask user for bid or take it from argument\n bid = args.bid if args.bid else bidding.ask_bid(tx_len)\n\n # API transmission order\n order = ApiOrder(server_addr, tls_cert=args.tls_cert, tls_key=args.tls_key)\n res = order.send(msg.get_data(), bid)\n print()\n\n # The API servers (except the gossip and btc-src instances) should return a\n # Lightning invoice for the transmission order\n if (server_addr != server_map['gossip']\n and server_addr != server_map['btc-src']):\n payreq = res[\"lightning_invoice\"][\"payreq\"]\n\n # Print QR code\n try:\n qr = qrcode.QRCode()\n qr.add_data(payreq)\n qr.print_ascii()\n except UnicodeError:\n qr.print_tty()\n\n # Execute arbitrary command with the Lightning invoice\n if (args.invoice_exec):\n cmd = shlex.split(args.invoice_exec.replace(\"{}\", payreq))\n logger.debug(\"Execute:\\n> {}\".format(\" \".join(cmd)))\n subprocess.run(cmd)\n\n # Wait until the transmission completes (after the ground station confirms\n # reception). Stop if it is canceled.\n if (args.no_wait):\n return\n\n try:\n target_state = ['sent', 'cancelled']\n order.wait_state(target_state)\n except KeyboardInterrupt:\n pass","function_tokens":["def","send","(","args",")",":","gnupghome","=","os",".","path",".","join","(","args",".","cfg_dir",",","args",".","gnupghome",")","server_addr","=","_get_server_addr","(","args",".","net",",","args",".","server",")","# Instantiate the GPG wrapper object if running with encryption or signing","if","(","not","args",".","plaintext","or","args",".","sign",")",":","gpg","=","Gpg","(","gnupghome",",","interactive","=","True",")","config_keyring","(","gpg",")","else",":","gpg","=","None","# A passphrase is required if signing","if","(","args",".","sign","and","(","not","args",".","no_password",")",")",":","gpg",".","prompt_passphrase","(","'Password to private key used for message '","'signing: '",")","# File or text message to send over satellite","if","(","args",".","file","is","None",")",":","if","(","args",".","message","is","None",")",":","data","=","input","(","\"Type a message: \"",")",".","encode","(",")","print","(",")","else",":","data","=","args",".","message",".","encode","(",")","basename","=","None","else",":","basename","=","os",".","path",".","basename","(","args",".","file",")","with","open","(","args",".","file",",","'rb'",")","as","f",":","data","=","f",".","read","(",")","assert","(","len","(","data",")",">","0",")",",","\"Empty {}\"",".","format","(","\"file\"","if","args",".","file","else","\"message\"",")","# Put file or text within an API message","msg","=","api_msg",".","generate","(","data",",","filename","=","basename",",","plaintext","=","args",".","plaintext",",","encapsulate","=","(","not","args",".","send_raw",")",",","sign","=","args",".","sign",",","fec","=","args",".","fec",",","gpg","=","gpg",",","recipient","=","args",".","recipient",",","trust","=","args",".","trust",",","sign_key","=","args",".","sign_key",",","fec_overhead","=","args",".","fec_overhead",")","# Actual number of bytes used for satellite transmission","tx_len","=","calc_ota_msg_len","(","msg",".","get_length","(",")",")","logger",".","info","(","\"Satellite transmission will use %d bytes\"","%","(","tx_len",")",")","# Ask user for bid or take it from argument","bid","=","args",".","bid","if","args",".","bid","else","bidding",".","ask_bid","(","tx_len",")","# API transmission order","order","=","ApiOrder","(","server_addr",",","tls_cert","=","args",".","tls_cert",",","tls_key","=","args",".","tls_key",")","res","=","order",".","send","(","msg",".","get_data","(",")",",","bid",")","print","(",")","# The API servers (except the gossip and btc-src instances) should return a","# Lightning invoice for the transmission order","if","(","server_addr","!=","server_map","[","'gossip'","]","and","server_addr","!=","server_map","[","'btc-src'","]",")",":","payreq","=","res","[","\"lightning_invoice\"","]","[","\"payreq\"","]","# Print QR code","try",":","qr","=","qrcode",".","QRCode","(",")","qr",".","add_data","(","payreq",")","qr",".","print_ascii","(",")","except","UnicodeError",":","qr",".","print_tty","(",")","# Execute arbitrary command with the Lightning invoice","if","(","args",".","invoice_exec",")",":","cmd","=","shlex",".","split","(","args",".","invoice_exec",".","replace","(","\"{}\"",",","payreq",")",")","logger",".","debug","(","\"Execute:\\n> {}\"",".","format","(","\" \"",".","join","(","cmd",")",")",")","subprocess",".","run","(","cmd",")","# Wait until the transmission completes (after the ground station confirms","# reception). Stop if it is canceled.","if","(","args",".","no_wait",")",":","return","try",":","target_state","=","[","'sent'",",","'cancelled'","]","order",".","wait_state","(","target_state",")","except","KeyboardInterrupt",":","pass"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L60-L147"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"listen","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Listen to API messages received over satellite","docstring_summary":"Listen to API messages received over satellite","docstring_tokens":["Listen","to","API","messages","received","over","satellite"],"function":"def listen(args):\n \"\"\"Listen to API messages received over satellite\"\"\"\n gnupghome = os.path.join(args.cfg_dir, args.gnupghome)\n download_dir = os.path.join(args.cfg_dir, \"api\", \"downloads\")\n\n # Override some options based on the mutual exclusive --gossip and\n # --btc-src arguments, if present\n if (args.gossip):\n channel = ApiChannel.GOSSIP.value\n server_addr = server_map['gossip']\n args.plaintext = True\n elif (args.btc_src):\n channel = ApiChannel.BTC_SRC.value\n server_addr = server_map['btc-src']\n args.plaintext = True\n else:\n channel = args.channel\n server_addr = _get_server_addr(args.net, args.server)\n\n historian_cli = os.path.join(args.historian_path, 'historian-cli') \\\n if (args.historian_path) else 'historian-cli'\n\n # Argument validation and special cases\n if (args.gossip):\n if (which(historian_cli) is None):\n logger.error(\"Option --gossip requires the historian-cli \"\n \"application but could not find it\")\n logger.info(\"Use option --historian-path to specify the path to \"\n \"historian-cli\")\n raise ValueError(\"Could not find the historian-cli application\")\n\n if (args.stdout):\n raise ValueError(\"Argument --gossip is not allowed with argument \"\n \"--stdout\")\n elif (args.no_save):\n raise ValueError(\"Argument --gossip is not allowed with argument \"\n \"--no-save\")\n\n gossip_opts = {\n 'cli': historian_cli,\n 'dest': args.historian_destination\n }\n else:\n gossip_opts = None\n\n _warn_common_overrides(args) # warn args overridden by --gossip\/--btc-src\n\n if (args.exec):\n # Do not support the option in plaintext mode\n if (args.plaintext):\n raise ValueError(\"Option --exec is not allowed in plaintext mode\")\n\n # Require either --sender or --insecure\n if (args.sender is None and not args.insecure):\n raise ValueError(\"Option --exec requires a specified --sender\")\n\n # Warn about unsafe commands\n base_exec_cmd = shlex.split(args.exec)[0]\n unsafe_cmds = [\"\/bin\/bash\", \"bash\", \"\/bin\/sh\", \"sh\", \"rm\"]\n if (base_exec_cmd in unsafe_cmds):\n logger.warning(\"Running {} on --exec is considered unsafe\".format(\n base_exec_cmd))\n\n # GPG wrapper object\n if (not args.plaintext or args.sender):\n gpg = Gpg(gnupghome, interactive=True)\n config_keyring(gpg)\n else:\n gpg = None\n\n # Define the interface used to listen for messages\n if (args.interface):\n interface = args.interface\n elif (args.demo):\n interface = \"lo\"\n else:\n # Infer the interface based on the user's setup\n user_info = blocksatcli_config.read_cfg_file(args.cfg, args.cfg_dir)\n interface = blocksatcli_config.get_net_if(user_info)\n logger.info(\"Listening on interface: {}\".format(interface))\n logger.info(\"Downloads will be saved at: {}\".format(download_dir))\n\n # A passphrase is required for decryption (but not for signature\n # verification)\n if (not args.plaintext and not args.no_password):\n gpg.prompt_passphrase('GPG keyring password for decryption: ')\n\n # Listen continuously\n listen_loop = ApiListener()\n listen_loop.run(gpg,\n download_dir,\n args.sock_addr,\n interface,\n channel,\n args.plaintext,\n args.save_raw,\n sender=args.sender,\n stdout=args.stdout,\n no_save=args.no_save,\n echo=args.echo,\n exec_cmd=args.exec,\n gossip_opts=gossip_opts,\n server_addr=server_addr,\n tls_cert=args.tls_cert,\n tls_key=args.tls_key,\n region=args.region)","function_tokens":["def","listen","(","args",")",":","gnupghome","=","os",".","path",".","join","(","args",".","cfg_dir",",","args",".","gnupghome",")","download_dir","=","os",".","path",".","join","(","args",".","cfg_dir",",","\"api\"",",","\"downloads\"",")","# Override some options based on the mutual exclusive --gossip and","# --btc-src arguments, if present","if","(","args",".","gossip",")",":","channel","=","ApiChannel",".","GOSSIP",".","value","server_addr","=","server_map","[","'gossip'","]","args",".","plaintext","=","True","elif","(","args",".","btc_src",")",":","channel","=","ApiChannel",".","BTC_SRC",".","value","server_addr","=","server_map","[","'btc-src'","]","args",".","plaintext","=","True","else",":","channel","=","args",".","channel","server_addr","=","_get_server_addr","(","args",".","net",",","args",".","server",")","historian_cli","=","os",".","path",".","join","(","args",".","historian_path",",","'historian-cli'",")","if","(","args",".","historian_path",")","else","'historian-cli'","# Argument validation and special cases","if","(","args",".","gossip",")",":","if","(","which","(","historian_cli",")","is","None",")",":","logger",".","error","(","\"Option --gossip requires the historian-cli \"","\"application but could not find it\"",")","logger",".","info","(","\"Use option --historian-path to specify the path to \"","\"historian-cli\"",")","raise","ValueError","(","\"Could not find the historian-cli application\"",")","if","(","args",".","stdout",")",":","raise","ValueError","(","\"Argument --gossip is not allowed with argument \"","\"--stdout\"",")","elif","(","args",".","no_save",")",":","raise","ValueError","(","\"Argument --gossip is not allowed with argument \"","\"--no-save\"",")","gossip_opts","=","{","'cli'",":","historian_cli",",","'dest'",":","args",".","historian_destination","}","else",":","gossip_opts","=","None","_warn_common_overrides","(","args",")","# warn args overridden by --gossip\/--btc-src","if","(","args",".","exec",")",":","# Do not support the option in plaintext mode","if","(","args",".","plaintext",")",":","raise","ValueError","(","\"Option --exec is not allowed in plaintext mode\"",")","# Require either --sender or --insecure","if","(","args",".","sender","is","None","and","not","args",".","insecure",")",":","raise","ValueError","(","\"Option --exec requires a specified --sender\"",")","# Warn about unsafe commands","base_exec_cmd","=","shlex",".","split","(","args",".","exec",")","[","0","]","unsafe_cmds","=","[","\"\/bin\/bash\"",",","\"bash\"",",","\"\/bin\/sh\"",",","\"sh\"",",","\"rm\"","]","if","(","base_exec_cmd","in","unsafe_cmds",")",":","logger",".","warning","(","\"Running {} on --exec is considered unsafe\"",".","format","(","base_exec_cmd",")",")","# GPG wrapper object","if","(","not","args",".","plaintext","or","args",".","sender",")",":","gpg","=","Gpg","(","gnupghome",",","interactive","=","True",")","config_keyring","(","gpg",")","else",":","gpg","=","None","# Define the interface used to listen for messages","if","(","args",".","interface",")",":","interface","=","args",".","interface","elif","(","args",".","demo",")",":","interface","=","\"lo\"","else",":","# Infer the interface based on the user's setup","user_info","=","blocksatcli_config",".","read_cfg_file","(","args",".","cfg",",","args",".","cfg_dir",")","interface","=","blocksatcli_config",".","get_net_if","(","user_info",")","logger",".","info","(","\"Listening on interface: {}\"",".","format","(","interface",")",")","logger",".","info","(","\"Downloads will be saved at: {}\"",".","format","(","download_dir",")",")","# A passphrase is required for decryption (but not for signature","# verification)","if","(","not","args",".","plaintext","and","not","args",".","no_password",")",":","gpg",".","prompt_passphrase","(","'GPG keyring password for decryption: '",")","# Listen continuously","listen_loop","=","ApiListener","(",")","listen_loop",".","run","(","gpg",",","download_dir",",","args",".","sock_addr",",","interface",",","channel",",","args",".","plaintext",",","args",".","save_raw",",","sender","=","args",".","sender",",","stdout","=","args",".","stdout",",","no_save","=","args",".","no_save",",","echo","=","args",".","echo",",","exec_cmd","=","args",".","exec",",","gossip_opts","=","gossip_opts",",","server_addr","=","server_addr",",","tls_cert","=","args",".","tls_cert",",","tls_key","=","args",".","tls_key",",","region","=","args",".","region",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L150-L255"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"bump","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Bump the bid of an API order","docstring_summary":"Bump the bid of an API order","docstring_tokens":["Bump","the","bid","of","an","API","order"],"function":"def bump(args):\n \"\"\"Bump the bid of an API order\"\"\"\n server_addr = _get_server_addr(args.net, args.server)\n\n # Fetch the ApiOrder\n order = ApiOrder(server_addr, tls_cert=args.tls_cert, tls_key=args.tls_key)\n order.get(args.uuid, args.auth_token)\n\n # Bump bid\n try:\n res = order.bump(args.bid)\n except ValueError as e:\n logger.error(e)\n return\n\n # Print QR code\n qr = qrcode.QRCode()\n qr.add_data(res[\"lightning_invoice\"][\"payreq\"])\n qr.print_ascii()","function_tokens":["def","bump","(","args",")",":","server_addr","=","_get_server_addr","(","args",".","net",",","args",".","server",")","# Fetch the ApiOrder","order","=","ApiOrder","(","server_addr",",","tls_cert","=","args",".","tls_cert",",","tls_key","=","args",".","tls_key",")","order",".","get","(","args",".","uuid",",","args",".","auth_token",")","# Bump bid","try",":","res","=","order",".","bump","(","args",".","bid",")","except","ValueError","as","e",":","logger",".","error","(","e",")","return","# Print QR code","qr","=","qrcode",".","QRCode","(",")","qr",".","add_data","(","res","[","\"lightning_invoice\"","]","[","\"payreq\"","]",")","qr",".","print_ascii","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L258-L276"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"delete","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Cancel an API order","docstring_summary":"Cancel an API order","docstring_tokens":["Cancel","an","API","order"],"function":"def delete(args):\n \"\"\"Cancel an API order\"\"\"\n server_addr = _get_server_addr(args.net, args.server)\n\n # Fetch the ApiOrder\n order = ApiOrder(server_addr, tls_cert=args.tls_cert, tls_key=args.tls_key)\n order.get(args.uuid, args.auth_token)\n\n # Delete it\n order.delete()","function_tokens":["def","delete","(","args",")",":","server_addr","=","_get_server_addr","(","args",".","net",",","args",".","server",")","# Fetch the ApiOrder","order","=","ApiOrder","(","server_addr",",","tls_cert","=","args",".","tls_cert",",","tls_key","=","args",".","tls_key",")","order",".","get","(","args",".","uuid",",","args",".","auth_token",")","# Delete it","order",".","delete","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L279-L288"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"demo_rx","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Demo satellite receiver","docstring_summary":"Demo satellite receiver","docstring_tokens":["Demo","satellite","receiver"],"function":"def demo_rx(args):\n \"\"\"Demo satellite receiver\"\"\"\n\n # Override some options based on the mutual exclusive --gossip and\n # --btc-src arguments, if present\n if (args.gossip):\n server_addr = server_map['gossip']\n channel = ApiChannel.GOSSIP.value\n elif (args.btc_src):\n server_addr = server_map['btc-src']\n channel = ApiChannel.BTC_SRC.value\n else:\n server_addr = _get_server_addr(args.net, args.server)\n channel = args.channel\n\n # Argument validation and special cases\n _warn_common_overrides(args) # warn args overridden by --gossip\/--btc-src\n\n # Open one socket for each interface:\n socks = list()\n for interface in args.interface:\n sock = net.UdpSock(args.dest, interface, mcast_rx=False)\n sock.set_mcast_tx_opts(args.ttl, args.dscp)\n socks.append(sock)\n\n rx = DemoRx(server_addr, socks, args.bitrate, args.event, channel,\n args.regions, args.tls_cert, args.tls_key)\n rx.run()","function_tokens":["def","demo_rx","(","args",")",":","# Override some options based on the mutual exclusive --gossip and","# --btc-src arguments, if present","if","(","args",".","gossip",")",":","server_addr","=","server_map","[","'gossip'","]","channel","=","ApiChannel",".","GOSSIP",".","value","elif","(","args",".","btc_src",")",":","server_addr","=","server_map","[","'btc-src'","]","channel","=","ApiChannel",".","BTC_SRC",".","value","else",":","server_addr","=","_get_server_addr","(","args",".","net",",","args",".","server",")","channel","=","args",".","channel","# Argument validation and special cases","_warn_common_overrides","(","args",")","# warn args overridden by --gossip\/--btc-src","# Open one socket for each interface:","socks","=","list","(",")","for","interface","in","args",".","interface",":","sock","=","net",".","UdpSock","(","args",".","dest",",","interface",",","mcast_rx","=","False",")","sock",".","set_mcast_tx_opts","(","args",".","ttl",",","args",".","dscp",")","socks",".","append","(","sock",")","rx","=","DemoRx","(","server_addr",",","socks",",","args",".","bitrate",",","args",".","event",",","channel",",","args",".","regions",",","args",".","tls_cert",",","args",".","tls_key",")","rx",".","run","(",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L291-L318"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"subparser","parameters":"(subparsers)","argument_list":"","return_statement":"return p","docstring":"Subparser for usb command","docstring_summary":"Subparser for usb command","docstring_tokens":["Subparser","for","usb","command"],"function":"def subparser(subparsers):\n \"\"\"Subparser for usb command\"\"\"\n def channel_number(value):\n ivalue = int(value)\n if ivalue < 0 or ivalue > 255:\n raise ArgumentTypeError(\n \"Invalid API channel number {}. \"\n \"Choose number within [0, 256)\".format(value))\n return ivalue\n\n p = subparsers.add_parser('api',\n description=\"Blockstream Satellite API\",\n help='Blockstream Satellite API',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n # Common API app arguments\n p.add_argument(\n '-g',\n '--gnupghome',\n default=\".gnupg\",\n help=\"GnuPG home directory, by default created inside the config \"\n \"directory specified via --cfg-dir option\")\n server_addr = p.add_mutually_exclusive_group()\n server_addr.add_argument(\n '--net',\n choices=server_map.keys(),\n default=None,\n help=\"Choose between the Mainnet API server (main), the Testnet API \\\n server (test), the receive-only server used for Lightning gossip \\\n messages (gossip), or the receive-only server used for messages \\\n carrying the Bitcoin source code (btc-src)\")\n server_addr.add_argument('-s',\n '--server',\n default=server_map['main'],\n help=\"Satellite API server address\")\n p.add_argument(\n '--tls-cert',\n default=None,\n help=\"Certificate for client-side authentication with the API server\")\n p.add_argument(\n '--tls-key',\n default=None,\n help=\"Private key for client-side authentication with the API server\")\n p.set_defaults(func=print_help)\n\n subsubparsers = p.add_subparsers(title='subcommands',\n help='Target sub-command')\n\n # Config\n p1 = subsubparsers.add_parser(\n 'config',\n aliases=['cfg'],\n description=\"Configure GPG keys\",\n help=\"Configure GPG keys\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n p1.add_argument('-v',\n '--verbose',\n action='store_true',\n default=False,\n help=\"Verbose mode\")\n p1.set_defaults(func=config)\n\n # Sender\n p2 = subsubparsers.add_parser(\n 'send',\n aliases=['tx'],\n description=textwrap.dedent('''\\\n\n Sends a file or a text message to the Satellite API for transmission\n via Blockstream Satellite. By default, runs the following sequence: 1)\n encapsulates the message into a structure containing the data checksum\n and the file name; 2) encrypts the entire structure using GnuPG; and 3)\n posts to the encrypted object to the API server for transmission.\n\n '''),\n help=\"Broadcast message through the Satellite API\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n msg_group = p2.add_mutually_exclusive_group()\n msg_group.add_argument('-f', '--file', help='File to send through the API')\n msg_group.add_argument('-m',\n '--message',\n help='Text message to send through the API')\n p2.add_argument('--bid',\n default=None,\n type=int,\n help=\"Bid (in millisatoshis) for the message transmission\")\n p2.add_argument(\n '-r',\n '--recipient',\n default=None,\n help=\"Public key fingerprint of the desired recipient. If not \"\n \"defined, the recipient will be automatically set to the first \"\n \"public key in the keyring\")\n p2.add_argument(\n '--trust',\n default=False,\n action=\"store_true\",\n help=\"Assume that the recipient\\'s public key is fully trusted\")\n p2.add_argument('--sign',\n default=False,\n action=\"store_true\",\n help=\"Sign message in addition to encrypting it\")\n p2.add_argument(\n '--sign-key',\n default=None,\n help=\"Fingerprint of the private key to be used when signing the \"\n \"message. If not set, the default key from the keyring will be used\")\n p2.add_argument(\n '--send-raw',\n default=False,\n action=\"store_true\",\n help=\"Send the raw file or text message, i.e., without the data \"\n \"structure that includes the file name and checksum\")\n p2.add_argument(\n '--plaintext',\n default=False,\n action=\"store_true\",\n help=\"Send data in plaintext format, i.e., without encryption\")\n p2.add_argument(\n '--fec',\n default=False,\n action=\"store_true\",\n help=\"Send data with forward error correction (FEC) encoding\")\n p2.add_argument(\n '--fec-overhead',\n default=0.1,\n type=float,\n help=\"Target ratio between the overhead FEC chunks and the original \"\n \"chunks. For example, 0.1 implies one overhead (redundant) chunk for \"\n \"every 10 original chunks\")\n p2.add_argument(\n '--no-password',\n default=False,\n action=\"store_true\",\n help=\"Whether to access the GPG keyring without a password\")\n p2.add_argument(\n '--invoice-exec',\n help=\"Execute command with the Lightning invoice. Replaces the string \"\n \"\\'{}\\' with the Lightning bolt11 invoice string.\")\n p2.add_argument(\n '--no-wait',\n default=False,\n action=\"store_true\",\n help=\"Return immediately after submitting an API transmission order. \"\n \"Do not wait for the payment and transmission confirmations\")\n p2.set_defaults(func=send)\n\n # Listen\n p3 = subsubparsers.add_parser(\n 'listen',\n aliases=['rx'],\n description=textwrap.dedent('''\\\n\n Receives data sent over the Blockstream Satellite network through the\n Satellite API. By default, assumes that the incoming messages are\n generated by the \"send\" command, which transmits encapsulated and\n encrypted messages. Thus, it first attempts to decrypt the data using a\n local GnuPG key. Then, on successful decryption, this application\n validates the integrity of the data. In the end, it saves the file into\n the download directory.\n\n '''),\n help=\"Listen to API messages\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n p3.add_argument(\n '--sock-addr',\n default=defs.api_dst_addr,\n help=\"Multicast UDP address (ip:port) used to listen for API data\")\n intf_arg = p3.add_mutually_exclusive_group()\n intf_arg.add_argument('-i',\n '--interface',\n default=None,\n help=\"Network interface that receives API data\")\n intf_arg.add_argument(\n '-d',\n '--demo',\n action=\"store_true\",\n default=False,\n help=\"Use the same interface as the demo-rx tool, i.e., the loopback \"\n \"interface\")\n p3.add_argument(\n '-c',\n '--channel',\n default=ApiChannel.USER.value,\n type=channel_number,\n help=\"Listen to a specific API transmission channel. If set to 0, \"\n \"listen to all channels. By default, listen to user transmissions, \"\n \"which are sent on channel 1\")\n p3.add_argument(\n '--save-raw',\n default=False,\n action=\"store_true\",\n help=\"Save the raw decrypted data into the download directory while \"\n \"ignoring the existence of a data encapsulation structure\")\n p3.add_argument(\n '--plaintext',\n default=False,\n action=\"store_true\",\n help=\"Do not try to decrypt the incoming messages. Instead, assume \"\n \"that the incoming messages are in plaintext format and save them as \"\n \"individual files named with timestamps in the download directory. \"\n \"Note this option saves all incoming messages, including those \"\n \"broadcast by other users. In contrast, the default mode (without \"\n \"this option) only saves the messages that are successfully decrypted.\"\n )\n p3.add_argument(\n '--sender',\n default=None,\n help=\"Public key fingerprint of a target sender used to filter the \"\n \"incoming messages. When specified, the application processes only \"\n \"the messages that are digitally signed by the selected sender, \"\n \"including clearsigned messages.\")\n p3.add_argument('--no-password',\n default=False,\n action=\"store_true\",\n help=\"Set to access GPG keyring without a password\")\n p3.add_argument(\n '--echo',\n default=False,\n action='store_true',\n help=\"Print the contents of all incoming text messages to the \"\n \"console, as long as these messages are decodable in UTF-8\")\n stdout_exec_arg_group = p3.add_mutually_exclusive_group()\n stdout_exec_arg_group.add_argument(\n '--stdout',\n default=False,\n action='store_true',\n help=\"Serialize the received data to stdout instead of saving on a \"\n \"file\")\n stdout_exec_arg_group.add_argument(\n '--no-save',\n default=False,\n action='store_true',\n help=\"Do not save the files decoded from the received API messages\")\n stdout_exec_arg_group.add_argument(\n '--exec',\n help=\"Execute arbitrary shell command for each downloaded file. \"\n \"Use the magic string \\'{}\\' to represent the file path within the \"\n \"command. For instance, run \\\"--exec \\'cat {}\\'\\\" to print every \"\n \"incoming file to stdout. For security, this option must be used in \"\n \"conjunction with the --sender option to limit the execution of the \"\n \"specified command to digitally signed messages from a specified \"\n \"sender only. See option --insecure for an alternative.\")\n p3.add_argument(\n '--insecure',\n default=False,\n action=\"store_true\",\n help=\"Run the --exec option while receiving messages from any sender. \"\n \"In this case, any successfully decrypted message (i.e., any message) \"\n \"encrypted using your public key will trigger the --exec command, \"\n \"which is considered insecure. Use at your own risk and avoid unsafe \"\n \"commands.\")\n btc_src_gossip_arg_group1 = p3.add_mutually_exclusive_group()\n btc_src_gossip_arg_group1.add_argument(\n '--gossip',\n default=False,\n action=\"store_true\",\n help=\"Configure the application to receive Lightning gossip snapshots \"\n \"and load them using the historian-cli application. This argument \"\n \"overrides the following options: 1) --plaintext (enabled); 2) \"\n \"--channel (set to {}); and 3) --server\/--net (set to {})\".format(\n ApiChannel.GOSSIP.value, server_map['gossip']))\n btc_src_gossip_arg_group1.add_argument(\n '--btc-src',\n default=False,\n action=\"store_true\",\n help=\"Configure the application to receive API messages carrying the \"\n \"Bitcoin Satellite and Bitcoin Core source codes. This argument \"\n \"overrides the following options: 1) --plaintext (enabled); 2) \"\n \"--channel (set to {}); and 3) --server\/--net (set to {})\".format(\n ApiChannel.BTC_SRC.value, server_map['btc-src']))\n p3.add_argument(\n '--historian-path',\n default=None,\n help=\"Path to the historian-cli application. If not set, look for \"\n \"historian-cli globally\")\n p3.add_argument(\n '--historian-destination',\n default=None,\n help=\"Destination for gossip snapshots, formatted as \"\n \"[nodeid]@[ipaddress]:[port]. If not set, historian-cli attempts to \"\n \"discover the destination automatically. This parameter is provided \"\n \"as a positional argument of command \\'historian-cli snapshot load\\', \"\n \"which is called for each downloaded file in gossip mode (i.e., when \"\n \"argument --gossip is set).\")\n p3.add_argument('-r',\n '--region',\n choices=range(0, 6),\n type=int,\n help=\"Coverage region for Rx confirmations\")\n p3.set_defaults(func=listen)\n\n # Bump\n p4 = subsubparsers.add_parser(\n 'bump',\n description=\"Bump bid of an API message order\",\n help=\"Bump bid of an API message order\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n p4.add_argument(\n '--bid',\n default=None,\n type=int,\n help=\"New bid (in millisatoshis) for the message transmission\")\n p4.add_argument('-u',\n '--uuid',\n default=None,\n help=\"API order's universally unique identifier (UUID)\")\n p4.add_argument('-a',\n '--auth-token',\n default=None,\n help=\"API order's authentication token\")\n p4.set_defaults(func=bump)\n\n # Delete\n p5 = subsubparsers.add_parser(\n 'delete',\n aliases=['del'],\n description=\"Delete API message order\",\n help=\"Delete API message order\",\n formatter_class=ArgumentDefaultsHelpFormatter)\n p5.add_argument('-u',\n '--uuid',\n default=None,\n help=\"API order's universally unique identifier (UUID)\")\n p5.add_argument('-a',\n '--auth-token',\n default=None,\n help=\"API order's authentication token\")\n p5.set_defaults(func=delete)\n\n # Demo receiver\n p6 = subsubparsers.add_parser(\n 'demo-rx',\n description=textwrap.dedent('''\\\n\n Demo Blockstream Satellite Receiver, used to test the API data listener\n application without an actual satellite receiver. The satellite\n receiver receives UDP packets sent over satellite and relays these\n packets to a host PC, where the API data listener application runs.\n This application, in turn, produces equivalent UDP packets, just like\n the satellite receiver would. The difference is that it fetches the\n data through the internet, rather than receiving via satellite.\n\n '''),\n help='Run demo satellite receiver',\n formatter_class=ArgumentDefaultsHelpFormatter)\n p6.add_argument(\n '-d',\n '--dest',\n default=defs.api_dst_addr,\n help=\"Destination address (ip:port) to which API data will be sent\")\n p6.add_argument(\n '-i',\n '--interface',\n nargs=\"+\",\n help=\"Network interface(s) over which to send the API data. If \\\n multiple interfaces are provided, the same packets are sent over all \\\n interfaces.\",\n default=[\"lo\"])\n p6.add_argument('-c',\n '--channel',\n default=ApiChannel.USER.value,\n type=channel_number,\n help=\"Target API transmission channel\")\n p6.add_argument('-r',\n '--regions',\n nargs=\"+\",\n choices=range(0, 6),\n type=int,\n help=\"Coverage region for Tx confirmations\")\n p6.add_argument('--ttl',\n type=int,\n default=1,\n help=\"Time-to-live to set on multicast packets\")\n p6.add_argument(\n '--dscp',\n type=int,\n default=0,\n help=\"Differentiated services code point (DSCP) to set on the output \\\n multicast IP packets\")\n p6.add_argument(\n '--bitrate',\n type=float,\n default=1000,\n help=\"Maximum bit rate in kbps of the output packet stream\")\n p6.add_argument('-e',\n '--event',\n choices=[\"transmitting\", \"sent\"],\n default=\"sent\",\n help='SSE event that should trigger packet transmissions')\n btc_src_gossip_arg_group2 = p6.add_mutually_exclusive_group()\n btc_src_gossip_arg_group2.add_argument(\n '--gossip',\n default=False,\n action=\"store_true\",\n help=\"Configure the application to fetch and relay Lightning gossip \"\n \"messages. This argument overrides option --channel (set to {}) and \"\n \"options --server\/--net (set to {})\".format(ApiChannel.GOSSIP.value,\n server_map['gossip']))\n btc_src_gossip_arg_group2.add_argument(\n '--btc-src',\n default=False,\n action=\"store_true\",\n help=\"Configure the application to fetch and relay messages carrying \"\n \"the Bitcoin Satellite and Bitcoin Core source codes. This argument \"\n \"overrides option --channel (set to {}) and options --server\/--net \"\n \"(set to {})\".format(ApiChannel.BTC_SRC.value, server_map['btc-src']))\n p6.set_defaults(func=demo_rx)\n\n return p","function_tokens":["def","subparser","(","subparsers",")",":","def","channel_number","(","value",")",":","ivalue","=","int","(","value",")","if","ivalue","<","0","or","ivalue",">","255",":","raise","ArgumentTypeError","(","\"Invalid API channel number {}. \"","\"Choose number within [0, 256)\"",".","format","(","value",")",")","return","ivalue","p","=","subparsers",".","add_parser","(","'api'",",","description","=","\"Blockstream Satellite API\"",",","help","=","'Blockstream Satellite API'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","# Common API app arguments","p",".","add_argument","(","'-g'",",","'--gnupghome'",",","default","=","\".gnupg\"",",","help","=","\"GnuPG home directory, by default created inside the config \"","\"directory specified via --cfg-dir option\"",")","server_addr","=","p",".","add_mutually_exclusive_group","(",")","server_addr",".","add_argument","(","'--net'",",","choices","=","server_map",".","keys","(",")",",","default","=","None",",","help","=","\"Choose between the Mainnet API server (main), the Testnet API \\\n server (test), the receive-only server used for Lightning gossip \\\n messages (gossip), or the receive-only server used for messages \\\n carrying the Bitcoin source code (btc-src)\"",")","server_addr",".","add_argument","(","'-s'",",","'--server'",",","default","=","server_map","[","'main'","]",",","help","=","\"Satellite API server address\"",")","p",".","add_argument","(","'--tls-cert'",",","default","=","None",",","help","=","\"Certificate for client-side authentication with the API server\"",")","p",".","add_argument","(","'--tls-key'",",","default","=","None",",","help","=","\"Private key for client-side authentication with the API server\"",")","p",".","set_defaults","(","func","=","print_help",")","subsubparsers","=","p",".","add_subparsers","(","title","=","'subcommands'",",","help","=","'Target sub-command'",")","# Config","p1","=","subsubparsers",".","add_parser","(","'config'",",","aliases","=","[","'cfg'","]",",","description","=","\"Configure GPG keys\"",",","help","=","\"Configure GPG keys\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p1",".","add_argument","(","'-v'",",","'--verbose'",",","action","=","'store_true'",",","default","=","False",",","help","=","\"Verbose mode\"",")","p1",".","set_defaults","(","func","=","config",")","# Sender","p2","=","subsubparsers",".","add_parser","(","'send'",",","aliases","=","[","'tx'","]",",","description","=","textwrap",".","dedent","(","'''\\\n\n Sends a file or a text message to the Satellite API for transmission\n via Blockstream Satellite. By default, runs the following sequence: 1)\n encapsulates the message into a structure containing the data checksum\n and the file name; 2) encrypts the entire structure using GnuPG; and 3)\n posts to the encrypted object to the API server for transmission.\n\n '''",")",",","help","=","\"Broadcast message through the Satellite API\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","msg_group","=","p2",".","add_mutually_exclusive_group","(",")","msg_group",".","add_argument","(","'-f'",",","'--file'",",","help","=","'File to send through the API'",")","msg_group",".","add_argument","(","'-m'",",","'--message'",",","help","=","'Text message to send through the API'",")","p2",".","add_argument","(","'--bid'",",","default","=","None",",","type","=","int",",","help","=","\"Bid (in millisatoshis) for the message transmission\"",")","p2",".","add_argument","(","'-r'",",","'--recipient'",",","default","=","None",",","help","=","\"Public key fingerprint of the desired recipient. If not \"","\"defined, the recipient will be automatically set to the first \"","\"public key in the keyring\"",")","p2",".","add_argument","(","'--trust'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Assume that the recipient\\'s public key is fully trusted\"",")","p2",".","add_argument","(","'--sign'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Sign message in addition to encrypting it\"",")","p2",".","add_argument","(","'--sign-key'",",","default","=","None",",","help","=","\"Fingerprint of the private key to be used when signing the \"","\"message. If not set, the default key from the keyring will be used\"",")","p2",".","add_argument","(","'--send-raw'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Send the raw file or text message, i.e., without the data \"","\"structure that includes the file name and checksum\"",")","p2",".","add_argument","(","'--plaintext'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Send data in plaintext format, i.e., without encryption\"",")","p2",".","add_argument","(","'--fec'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Send data with forward error correction (FEC) encoding\"",")","p2",".","add_argument","(","'--fec-overhead'",",","default","=","0.1",",","type","=","float",",","help","=","\"Target ratio between the overhead FEC chunks and the original \"","\"chunks. For example, 0.1 implies one overhead (redundant) chunk for \"","\"every 10 original chunks\"",")","p2",".","add_argument","(","'--no-password'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Whether to access the GPG keyring without a password\"",")","p2",".","add_argument","(","'--invoice-exec'",",","help","=","\"Execute command with the Lightning invoice. Replaces the string \"","\"\\'{}\\' with the Lightning bolt11 invoice string.\"",")","p2",".","add_argument","(","'--no-wait'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Return immediately after submitting an API transmission order. \"","\"Do not wait for the payment and transmission confirmations\"",")","p2",".","set_defaults","(","func","=","send",")","# Listen","p3","=","subsubparsers",".","add_parser","(","'listen'",",","aliases","=","[","'rx'","]",",","description","=","textwrap",".","dedent","(","'''\\\n\n Receives data sent over the Blockstream Satellite network through the\n Satellite API. By default, assumes that the incoming messages are\n generated by the \"send\" command, which transmits encapsulated and\n encrypted messages. Thus, it first attempts to decrypt the data using a\n local GnuPG key. Then, on successful decryption, this application\n validates the integrity of the data. In the end, it saves the file into\n the download directory.\n\n '''",")",",","help","=","\"Listen to API messages\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p3",".","add_argument","(","'--sock-addr'",",","default","=","defs",".","api_dst_addr",",","help","=","\"Multicast UDP address (ip:port) used to listen for API data\"",")","intf_arg","=","p3",".","add_mutually_exclusive_group","(",")","intf_arg",".","add_argument","(","'-i'",",","'--interface'",",","default","=","None",",","help","=","\"Network interface that receives API data\"",")","intf_arg",".","add_argument","(","'-d'",",","'--demo'",",","action","=","\"store_true\"",",","default","=","False",",","help","=","\"Use the same interface as the demo-rx tool, i.e., the loopback \"","\"interface\"",")","p3",".","add_argument","(","'-c'",",","'--channel'",",","default","=","ApiChannel",".","USER",".","value",",","type","=","channel_number",",","help","=","\"Listen to a specific API transmission channel. If set to 0, \"","\"listen to all channels. By default, listen to user transmissions, \"","\"which are sent on channel 1\"",")","p3",".","add_argument","(","'--save-raw'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Save the raw decrypted data into the download directory while \"","\"ignoring the existence of a data encapsulation structure\"",")","p3",".","add_argument","(","'--plaintext'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Do not try to decrypt the incoming messages. Instead, assume \"","\"that the incoming messages are in plaintext format and save them as \"","\"individual files named with timestamps in the download directory. \"","\"Note this option saves all incoming messages, including those \"","\"broadcast by other users. In contrast, the default mode (without \"","\"this option) only saves the messages that are successfully decrypted.\"",")","p3",".","add_argument","(","'--sender'",",","default","=","None",",","help","=","\"Public key fingerprint of a target sender used to filter the \"","\"incoming messages. When specified, the application processes only \"","\"the messages that are digitally signed by the selected sender, \"","\"including clearsigned messages.\"",")","p3",".","add_argument","(","'--no-password'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Set to access GPG keyring without a password\"",")","p3",".","add_argument","(","'--echo'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Print the contents of all incoming text messages to the \"","\"console, as long as these messages are decodable in UTF-8\"",")","stdout_exec_arg_group","=","p3",".","add_mutually_exclusive_group","(",")","stdout_exec_arg_group",".","add_argument","(","'--stdout'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Serialize the received data to stdout instead of saving on a \"","\"file\"",")","stdout_exec_arg_group",".","add_argument","(","'--no-save'",",","default","=","False",",","action","=","'store_true'",",","help","=","\"Do not save the files decoded from the received API messages\"",")","stdout_exec_arg_group",".","add_argument","(","'--exec'",",","help","=","\"Execute arbitrary shell command for each downloaded file. \"","\"Use the magic string \\'{}\\' to represent the file path within the \"","\"command. For instance, run \\\"--exec \\'cat {}\\'\\\" to print every \"","\"incoming file to stdout. For security, this option must be used in \"","\"conjunction with the --sender option to limit the execution of the \"","\"specified command to digitally signed messages from a specified \"","\"sender only. See option --insecure for an alternative.\"",")","p3",".","add_argument","(","'--insecure'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Run the --exec option while receiving messages from any sender. \"","\"In this case, any successfully decrypted message (i.e., any message) \"","\"encrypted using your public key will trigger the --exec command, \"","\"which is considered insecure. Use at your own risk and avoid unsafe \"","\"commands.\"",")","btc_src_gossip_arg_group1","=","p3",".","add_mutually_exclusive_group","(",")","btc_src_gossip_arg_group1",".","add_argument","(","'--gossip'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Configure the application to receive Lightning gossip snapshots \"","\"and load them using the historian-cli application. This argument \"","\"overrides the following options: 1) --plaintext (enabled); 2) \"","\"--channel (set to {}); and 3) --server\/--net (set to {})\"",".","format","(","ApiChannel",".","GOSSIP",".","value",",","server_map","[","'gossip'","]",")",")","btc_src_gossip_arg_group1",".","add_argument","(","'--btc-src'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Configure the application to receive API messages carrying the \"","\"Bitcoin Satellite and Bitcoin Core source codes. This argument \"","\"overrides the following options: 1) --plaintext (enabled); 2) \"","\"--channel (set to {}); and 3) --server\/--net (set to {})\"",".","format","(","ApiChannel",".","BTC_SRC",".","value",",","server_map","[","'btc-src'","]",")",")","p3",".","add_argument","(","'--historian-path'",",","default","=","None",",","help","=","\"Path to the historian-cli application. If not set, look for \"","\"historian-cli globally\"",")","p3",".","add_argument","(","'--historian-destination'",",","default","=","None",",","help","=","\"Destination for gossip snapshots, formatted as \"","\"[nodeid]@[ipaddress]:[port]. If not set, historian-cli attempts to \"","\"discover the destination automatically. This parameter is provided \"","\"as a positional argument of command \\'historian-cli snapshot load\\', \"","\"which is called for each downloaded file in gossip mode (i.e., when \"","\"argument --gossip is set).\"",")","p3",".","add_argument","(","'-r'",",","'--region'",",","choices","=","range","(","0",",","6",")",",","type","=","int",",","help","=","\"Coverage region for Rx confirmations\"",")","p3",".","set_defaults","(","func","=","listen",")","# Bump","p4","=","subsubparsers",".","add_parser","(","'bump'",",","description","=","\"Bump bid of an API message order\"",",","help","=","\"Bump bid of an API message order\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p4",".","add_argument","(","'--bid'",",","default","=","None",",","type","=","int",",","help","=","\"New bid (in millisatoshis) for the message transmission\"",")","p4",".","add_argument","(","'-u'",",","'--uuid'",",","default","=","None",",","help","=","\"API order's universally unique identifier (UUID)\"",")","p4",".","add_argument","(","'-a'",",","'--auth-token'",",","default","=","None",",","help","=","\"API order's authentication token\"",")","p4",".","set_defaults","(","func","=","bump",")","# Delete","p5","=","subsubparsers",".","add_parser","(","'delete'",",","aliases","=","[","'del'","]",",","description","=","\"Delete API message order\"",",","help","=","\"Delete API message order\"",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p5",".","add_argument","(","'-u'",",","'--uuid'",",","default","=","None",",","help","=","\"API order's universally unique identifier (UUID)\"",")","p5",".","add_argument","(","'-a'",",","'--auth-token'",",","default","=","None",",","help","=","\"API order's authentication token\"",")","p5",".","set_defaults","(","func","=","delete",")","# Demo receiver","p6","=","subsubparsers",".","add_parser","(","'demo-rx'",",","description","=","textwrap",".","dedent","(","'''\\\n\n Demo Blockstream Satellite Receiver, used to test the API data listener\n application without an actual satellite receiver. The satellite\n receiver receives UDP packets sent over satellite and relays these\n packets to a host PC, where the API data listener application runs.\n This application, in turn, produces equivalent UDP packets, just like\n the satellite receiver would. The difference is that it fetches the\n data through the internet, rather than receiving via satellite.\n\n '''",")",",","help","=","'Run demo satellite receiver'",",","formatter_class","=","ArgumentDefaultsHelpFormatter",")","p6",".","add_argument","(","'-d'",",","'--dest'",",","default","=","defs",".","api_dst_addr",",","help","=","\"Destination address (ip:port) to which API data will be sent\"",")","p6",".","add_argument","(","'-i'",",","'--interface'",",","nargs","=","\"+\"",",","help","=","\"Network interface(s) over which to send the API data. If \\\n multiple interfaces are provided, the same packets are sent over all \\\n interfaces.\"",",","default","=","[","\"lo\"","]",")","p6",".","add_argument","(","'-c'",",","'--channel'",",","default","=","ApiChannel",".","USER",".","value",",","type","=","channel_number",",","help","=","\"Target API transmission channel\"",")","p6",".","add_argument","(","'-r'",",","'--regions'",",","nargs","=","\"+\"",",","choices","=","range","(","0",",","6",")",",","type","=","int",",","help","=","\"Coverage region for Tx confirmations\"",")","p6",".","add_argument","(","'--ttl'",",","type","=","int",",","default","=","1",",","help","=","\"Time-to-live to set on multicast packets\"",")","p6",".","add_argument","(","'--dscp'",",","type","=","int",",","default","=","0",",","help","=","\"Differentiated services code point (DSCP) to set on the output \\\n multicast IP packets\"",")","p6",".","add_argument","(","'--bitrate'",",","type","=","float",",","default","=","1000",",","help","=","\"Maximum bit rate in kbps of the output packet stream\"",")","p6",".","add_argument","(","'-e'",",","'--event'",",","choices","=","[","\"transmitting\"",",","\"sent\"","]",",","default","=","\"sent\"",",","help","=","'SSE event that should trigger packet transmissions'",")","btc_src_gossip_arg_group2","=","p6",".","add_mutually_exclusive_group","(",")","btc_src_gossip_arg_group2",".","add_argument","(","'--gossip'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Configure the application to fetch and relay Lightning gossip \"","\"messages. This argument overrides option --channel (set to {}) and \"","\"options --server\/--net (set to {})\"",".","format","(","ApiChannel",".","GOSSIP",".","value",",","server_map","[","'gossip'","]",")",")","btc_src_gossip_arg_group2",".","add_argument","(","'--btc-src'",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"Configure the application to fetch and relay messages carrying \"","\"the Bitcoin Satellite and Bitcoin Core source codes. This argument \"","\"overrides option --channel (set to {}) and options --server\/--net \"","\"(set to {})\"",".","format","(","ApiChannel",".","BTC_SRC",".","value",",","server_map","[","'btc-src'","]",")",")","p6",".","set_defaults","(","func","=","demo_rx",")","return","p"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L321-L730"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/api.py","language":"python","identifier":"print_help","parameters":"(args)","argument_list":"","return_statement":"","docstring":"Re-create argparse's help menu for the api command","docstring_summary":"Re-create argparse's help menu for the api command","docstring_tokens":["Re","-","create","argparse","s","help","menu","for","the","api","command"],"function":"def print_help(args):\n \"\"\"Re-create argparse's help menu for the api command\"\"\"\n parser = ArgumentParser()\n subparsers = parser.add_subparsers(title='', help='')\n parser = subparser(subparsers)\n print(parser.format_help())","function_tokens":["def","print_help","(","args",")",":","parser","=","ArgumentParser","(",")","subparsers","=","parser",".","add_subparsers","(","title","=","''",",","help","=","''",")","parser","=","subparser","(","subparsers",")","print","(","parser",".","format_help","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/api.py#L733-L738"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"calc_ota_msg_len","parameters":"(msg_len)","argument_list":"","return_statement":"return total_mpe_overhead + total_overhead + msg_len","docstring":"Compute the number of bytes sent over-the-air (OTA) for an API message\n\n The API message is carried by Blocksat Packets, sent in the payload of UDP\n datagrams over IPv4, with a layer-2 MTU of 1500 bytes, and, ultimately,\n transported over MPE. If the message size is such that the UDP\/IPv4 packet\n exceeds the layer-2 MTU, fragmentation is not handled at the IP level but\n instead at application layer, i.e., at the Blocksat Packet protocol level.\n\n Args:\n msg_len : Length of the API message to be transmitted","docstring_summary":"Compute the number of bytes sent over-the-air (OTA) for an API message","docstring_tokens":["Compute","the","number","of","bytes","sent","over","-","the","-","air","(","OTA",")","for","an","API","message"],"function":"def calc_ota_msg_len(msg_len):\n \"\"\"Compute the number of bytes sent over-the-air (OTA) for an API message\n\n The API message is carried by Blocksat Packets, sent in the payload of UDP\n datagrams over IPv4, with a layer-2 MTU of 1500 bytes, and, ultimately,\n transported over MPE. If the message size is such that the UDP\/IPv4 packet\n exceeds the layer-2 MTU, fragmentation is not handled at the IP level but\n instead at application layer, i.e., at the Blocksat Packet protocol level.\n\n Args:\n msg_len : Length of the API message to be transmitted\n\n \"\"\"\n # Is it going to be fragmented?\n n_frags = ceil(msg_len \/ MAX_PAYLOAD)\n\n # Including all fragments, the total Blocksat + UDP + IPv4 overhead is:\n total_overhead = (UDP_IP_HEADER + HEADER_LEN) * n_frags\n\n # Total overhead at MPE layer:\n mpe_header = 16\n total_mpe_overhead = mpe_header * n_frags\n\n return total_mpe_overhead + total_overhead + msg_len","function_tokens":["def","calc_ota_msg_len","(","msg_len",")",":","# Is it going to be fragmented?","n_frags","=","ceil","(","msg_len","\/","MAX_PAYLOAD",")","# Including all fragments, the total Blocksat + UDP + IPv4 overhead is:","total_overhead","=","(","UDP_IP_HEADER","+","HEADER_LEN",")","*","n_frags","# Total overhead at MPE layer:","mpe_header","=","16","total_mpe_overhead","=","mpe_header","*","n_frags","return","total_mpe_overhead","+","total_overhead","+","msg_len"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L352-L375"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPkt.pack","parameters":"(self)","argument_list":"","return_statement":"return header + self.payload","docstring":"Form Blocksat Packet","docstring_summary":"Form Blocksat Packet","docstring_tokens":["Form","Blocksat","Packet"],"function":"def pack(self):\n \"\"\"Form Blocksat Packet\n \"\"\"\n # Assert the \"more fragments\" (MF) bit if this isn't the last fragment\n octet_0 = API_TYPE_MORE_FRAG if self.more_frags else API_TYPE_LAST_FRAG\n header = struct.pack(HEADER_FORMAT, octet_0, self.chan_num,\n self.frag_num, self.seq_num)\n return header + self.payload","function_tokens":["def","pack","(","self",")",":","# Assert the \"more fragments\" (MF) bit if this isn't the last fragment","octet_0","=","API_TYPE_MORE_FRAG","if","self",".","more_frags","else","API_TYPE_LAST_FRAG","header","=","struct",".","pack","(","HEADER_FORMAT",",","octet_0",",","self",".","chan_num",",","self",".","frag_num",",","self",".","seq_num",")","return","header","+","self",".","payload"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L77-L84"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPkt.unpack","parameters":"(self, udp_payload)","argument_list":"","return_statement":"","docstring":"Unpack Blocksat Packet from UDP payload\n\n Args:\n udp_payload : UDP payload received via socket (bytes)\n\n Returns:\n Tuple with the Blocksat Packet's payload (bytes) and sequence\n number.","docstring_summary":"Unpack Blocksat Packet from UDP payload","docstring_tokens":["Unpack","Blocksat","Packet","from","UDP","payload"],"function":"def unpack(self, udp_payload):\n \"\"\"Unpack Blocksat Packet from UDP payload\n\n Args:\n udp_payload : UDP payload received via socket (bytes)\n\n Returns:\n Tuple with the Blocksat Packet's payload (bytes) and sequence\n number.\n\n \"\"\"\n assert (isinstance(udp_payload, bytes))\n assert (len(udp_payload) >= HEADER_LEN)\n\n # Separate header and payload\n header = udp_payload[:HEADER_LEN]\n self.payload = udp_payload[HEADER_LEN:]\n\n # Parse header\n octet_0, self.chan_num, self.frag_num, self.seq_num = struct.unpack(\n HEADER_FORMAT, header)\n\n # Sanity check\n assert (ord(octet_0) & 1), \"Not an API packet\"\n\n # Are there more fragments coming?\n self.more_frags = bool(ord(octet_0) & ord(b'\\x80'))\n\n logger.debug(\"BlocksatPkt: Seq Num: {} \/ Frag Num: {} \/ MF: {}\".format(\n self.seq_num, self.frag_num, self.more_frags))","function_tokens":["def","unpack","(","self",",","udp_payload",")",":","assert","(","isinstance","(","udp_payload",",","bytes",")",")","assert","(","len","(","udp_payload",")",">=","HEADER_LEN",")","# Separate header and payload","header","=","udp_payload","[",":","HEADER_LEN","]","self",".","payload","=","udp_payload","[","HEADER_LEN",":","]","# Parse header","octet_0",",","self",".","chan_num",",","self",".","frag_num",",","self",".","seq_num","=","struct",".","unpack","(","HEADER_FORMAT",",","header",")","# Sanity check","assert","(","ord","(","octet_0",")","&","1",")",",","\"Not an API packet\"","# Are there more fragments coming?","self",".","more_frags","=","bool","(","ord","(","octet_0",")","&","ord","(","b'\\x80'",")",")","logger",".","debug","(","\"BlocksatPkt: Seq Num: {} \/ Frag Num: {} \/ MF: {}\"",".","format","(","self",".","seq_num",",","self",".","frag_num",",","self",".","more_frags",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L86-L115"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.__init__","parameters":"(self, timeout=7200)","argument_list":"","return_statement":"","docstring":"BlocksatPktHandler Constructor\n\n Args:\n timeout : Timeout in seconds to remove old pending fragments.","docstring_summary":"BlocksatPktHandler Constructor","docstring_tokens":["BlocksatPktHandler","Constructor"],"function":"def __init__(self, timeout=7200):\n \"\"\"BlocksatPktHandler Constructor\n\n Args:\n timeout : Timeout in seconds to remove old pending fragments.\n\n \"\"\"\n self.frag_map = {}\n self.timeout = timeout","function_tokens":["def","__init__","(","self",",","timeout","=","7200",")",":","self",".","frag_map","=","{","}","self",".","timeout","=","timeout"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L130-L138"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler._check_gaps","parameters":"(self, seq_num)","argument_list":"","return_statement":"return True","docstring":"Check if there is any fragment number gap\n\n Returns:\n (bool) True when there are no gaps (everything is OK).","docstring_summary":"Check if there is any fragment number gap","docstring_tokens":["Check","if","there","is","any","fragment","number","gap"],"function":"def _check_gaps(self, seq_num):\n \"\"\"Check if there is any fragment number gap\n\n Returns:\n (bool) True when there are no gaps (everything is OK).\n\n \"\"\"\n frag_idxs = sorted(self.frag_map[seq_num]['frags'].keys())\n for i, x in enumerate(frag_idxs):\n if (i == 0 and x != 0):\n if (x > 1):\n logger.warning(\"First {:d} fragments were lost\".format(x))\n else:\n logger.warning(\"First fragment was lost\")\n return False\n elif (i > 0 and x - frag_idxs[i - 1] != 1):\n logger.warning(\"Gap between fragment {:d} and fragment \"\n \"{:d}\".format(frag_idxs[i - 1], x))\n return False\n return True","function_tokens":["def","_check_gaps","(","self",",","seq_num",")",":","frag_idxs","=","sorted","(","self",".","frag_map","[","seq_num","]","[","'frags'","]",".","keys","(",")",")","for","i",",","x","in","enumerate","(","frag_idxs",")",":","if","(","i","==","0","and","x","!=","0",")",":","if","(","x",">","1",")",":","logger",".","warning","(","\"First {:d} fragments were lost\"",".","format","(","x",")",")","else",":","logger",".","warning","(","\"First fragment was lost\"",")","return","False","elif","(","i",">","0","and","x","-","frag_idxs","[","i","-","1","]","!=","1",")",":","logger",".","warning","(","\"Gap between fragment {:d} and fragment \"","\"{:d}\"",".","format","(","frag_idxs","[","i","-","1","]",",","x",")",")","return","False","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L140-L159"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler._check_ready","parameters":"(self, seq_num)","argument_list":"","return_statement":"return all([i in frags for i in range(i_last_frag)])","docstring":"Check if the collection of Blocksat Packets is ready to be decoded\n\n Returns:\n (bool) True when ready to be decoded.","docstring_summary":"Check if the collection of Blocksat Packets is ready to be decoded","docstring_tokens":["Check","if","the","collection","of","Blocksat","Packets","is","ready","to","be","decoded"],"function":"def _check_ready(self, seq_num):\n \"\"\"Check if the collection of Blocksat Packets is ready to be decoded\n\n Returns:\n (bool) True when ready to be decoded.\n\n \"\"\"\n # The message can only be ready when the last fragment is available:\n i_last_frag = self.frag_map[seq_num]['last_frag']\n if (i_last_frag is None):\n return False\n\n # Because packets can be processed out of order, check that all packets\n # before the last fragment are also available:\n frags = self.frag_map[seq_num]['frags'].keys()\n return all([i in frags for i in range(i_last_frag)])","function_tokens":["def","_check_ready","(","self",",","seq_num",")",":","# The message can only be ready when the last fragment is available:","i_last_frag","=","self",".","frag_map","[","seq_num","]","[","'last_frag'","]","if","(","i_last_frag","is","None",")",":","return","False","# Because packets can be processed out of order, check that all packets","# before the last fragment are also available:","frags","=","self",".","frag_map","[","seq_num","]","[","'frags'","]",".","keys","(",")","return","all","(","[","i","in","frags","for","i","in","range","(","i_last_frag",")","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L161-L176"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler._concat_pkt","parameters":"(self, pkt)","argument_list":"","return_statement":"","docstring":"Concatenate a single BlocksatPkt within a concatenation cache","docstring_summary":"Concatenate a single BlocksatPkt within a concatenation cache","docstring_tokens":["Concatenate","a","single","BlocksatPkt","within","a","concatenation","cache"],"function":"def _concat_pkt(self, pkt):\n \"\"\"Concatenate a single BlocksatPkt within a concatenation cache\"\"\"\n seq_num = pkt.seq_num\n\n # If it's an out-of-order packet, re-compute the concatenated\n # version. Otherwise, just append directly to the cache.\n if (self.frag_map[seq_num]['high_frag'] is not None\n and pkt.frag_num < self.frag_map[seq_num]['high_frag']):\n\n concat_msg = bytearray()\n for i_frag, frag in sorted(\n self.frag_map[seq_num]['frags'].items()):\n concat_msg += frag.payload\n\n self.frag_map[seq_num]['concat'] = concat_msg\n else:\n self.frag_map[seq_num]['concat'] += pkt.payload","function_tokens":["def","_concat_pkt","(","self",",","pkt",")",":","seq_num","=","pkt",".","seq_num","# If it's an out-of-order packet, re-compute the concatenated","# version. Otherwise, just append directly to the cache.","if","(","self",".","frag_map","[","seq_num","]","[","'high_frag'","]","is","not","None","and","pkt",".","frag_num","<","self",".","frag_map","[","seq_num","]","[","'high_frag'","]",")",":","concat_msg","=","bytearray","(",")","for","i_frag",",","frag","in","sorted","(","self",".","frag_map","[","seq_num","]","[","'frags'","]",".","items","(",")",")",":","concat_msg","+=","frag",".","payload","self",".","frag_map","[","seq_num","]","[","'concat'","]","=","concat_msg","else",":","self",".","frag_map","[","seq_num","]","[","'concat'","]","+=","pkt",".","payload"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L178-L194"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.append","parameters":"(self, pkt)","argument_list":"","return_statement":"return self._check_ready(pkt.seq_num)","docstring":"Append incoming BlocksatPkt\n\n Append the incoming Blocksat packet to the map of packets (fragments)\n pertaining to the same API message. Once the last fragment of a\n sequence comes, let the caller know that the API message is ready to be\n decoded.\n\n Args:\n pkt : Incoming BlocksatPkt\n\n Returns:\n (bool) True if the underlying ApiMsg is ready to be extracted from\n the corresponding collection of packets.","docstring_summary":"Append incoming BlocksatPkt","docstring_tokens":["Append","incoming","BlocksatPkt"],"function":"def append(self, pkt):\n \"\"\"Append incoming BlocksatPkt\n\n Append the incoming Blocksat packet to the map of packets (fragments)\n pertaining to the same API message. Once the last fragment of a\n sequence comes, let the caller know that the API message is ready to be\n decoded.\n\n Args:\n pkt : Incoming BlocksatPkt\n\n Returns:\n (bool) True if the underlying ApiMsg is ready to be extracted from\n the corresponding collection of packets.\n\n \"\"\"\n assert (isinstance(pkt, BlocksatPkt))\n\n if (pkt.seq_num not in self.frag_map):\n self.frag_map[pkt.seq_num] = {\n 'high_frag': None,\n 'last_frag': None,\n 'concat': bytearray()\n }\n self.frag_map[pkt.seq_num]['frags'] = {}\n\n # Do not process a repeated fragment\n if (pkt.frag_num in self.frag_map[pkt.seq_num]['frags']):\n logger.debug(\"BlocksatPktHandler: fragment {} has already \"\n \"been received\".format(pkt.frag_num))\n # Check if the repeated fragment actually has the same contents\n pre_existing_pkt = self.frag_map[pkt.seq_num]['frags'][\n pkt.frag_num]\n if (pkt.payload != pre_existing_pkt.payload):\n logger.warning(\n \"Got the same fragment twice but with different contents \"\n \"(frag_num: {}, seq_num: {})\".format(\n pkt.frag_num, pkt.seq_num))\n return self._check_ready(pkt.seq_num)\n\n self.frag_map[pkt.seq_num]['frags'][pkt.frag_num] = pkt\n\n # Timestamp the last fragment reception of this sequence number. Use\n # this timestamp to clean old fragments that were never decoded.\n self.frag_map[pkt.seq_num]['t_last'] = time.time()\n\n # Concatenate payload by payload instead of waiting to concatenate\n # everything in the end when the message is ready.\n self._concat_pkt(pkt)\n\n # Track the highest fragment number received so far. This information\n # is used to identify whether the concatenation cache needs to be\n # recomputed for out-of-order packets (see _concat_pkt()).\n if (self.frag_map[pkt.seq_num]['high_frag'] is None\n or pkt.frag_num > self.frag_map[pkt.seq_num]['high_frag']):\n self.frag_map[pkt.seq_num]['high_frag'] = pkt.frag_num\n\n # Track the last fragment of the sequence. This information is used to\n # more quickly verify whether the message is ready (see\n # _check_ready()).\n if (not pkt.more_frags):\n self.frag_map[pkt.seq_num]['last_frag'] = pkt.frag_num\n\n logger.debug(\"BlocksatPktHandler: Append fragment {}, \"\n \"Seq Num {}\".format(pkt.frag_num, pkt.seq_num))\n\n return self._check_ready(pkt.seq_num)","function_tokens":["def","append","(","self",",","pkt",")",":","assert","(","isinstance","(","pkt",",","BlocksatPkt",")",")","if","(","pkt",".","seq_num","not","in","self",".","frag_map",")",":","self",".","frag_map","[","pkt",".","seq_num","]","=","{","'high_frag'",":","None",",","'last_frag'",":","None",",","'concat'",":","bytearray","(",")","}","self",".","frag_map","[","pkt",".","seq_num","]","[","'frags'","]","=","{","}","# Do not process a repeated fragment","if","(","pkt",".","frag_num","in","self",".","frag_map","[","pkt",".","seq_num","]","[","'frags'","]",")",":","logger",".","debug","(","\"BlocksatPktHandler: fragment {} has already \"","\"been received\"",".","format","(","pkt",".","frag_num",")",")","# Check if the repeated fragment actually has the same contents","pre_existing_pkt","=","self",".","frag_map","[","pkt",".","seq_num","]","[","'frags'","]","[","pkt",".","frag_num","]","if","(","pkt",".","payload","!=","pre_existing_pkt",".","payload",")",":","logger",".","warning","(","\"Got the same fragment twice but with different contents \"","\"(frag_num: {}, seq_num: {})\"",".","format","(","pkt",".","frag_num",",","pkt",".","seq_num",")",")","return","self",".","_check_ready","(","pkt",".","seq_num",")","self",".","frag_map","[","pkt",".","seq_num","]","[","'frags'","]","[","pkt",".","frag_num","]","=","pkt","# Timestamp the last fragment reception of this sequence number. Use","# this timestamp to clean old fragments that were never decoded.","self",".","frag_map","[","pkt",".","seq_num","]","[","'t_last'","]","=","time",".","time","(",")","# Concatenate payload by payload instead of waiting to concatenate","# everything in the end when the message is ready.","self",".","_concat_pkt","(","pkt",")","# Track the highest fragment number received so far. This information","# is used to identify whether the concatenation cache needs to be","# recomputed for out-of-order packets (see _concat_pkt()).","if","(","self",".","frag_map","[","pkt",".","seq_num","]","[","'high_frag'","]","is","None","or","pkt",".","frag_num",">","self",".","frag_map","[","pkt",".","seq_num","]","[","'high_frag'","]",")",":","self",".","frag_map","[","pkt",".","seq_num","]","[","'high_frag'","]","=","pkt",".","frag_num","# Track the last fragment of the sequence. This information is used to","# more quickly verify whether the message is ready (see","# _check_ready()).","if","(","not","pkt",".","more_frags",")",":","self",".","frag_map","[","pkt",".","seq_num","]","[","'last_frag'","]","=","pkt",".","frag_num","logger",".","debug","(","\"BlocksatPktHandler: Append fragment {}, \"","\"Seq Num {}\"",".","format","(","pkt",".","frag_num",",","pkt",".","seq_num",")",")","return","self",".","_check_ready","(","pkt",".","seq_num",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L196-L262"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.get_frags","parameters":"(self, seq_num)","argument_list":"","return_statement":"return [x[1] for x in sorted(self.frag_map[seq_num]['frags'].items())]","docstring":"Get the Blocksat Packets sorted by fragment number","docstring_summary":"Get the Blocksat Packets sorted by fragment number","docstring_tokens":["Get","the","Blocksat","Packets","sorted","by","fragment","number"],"function":"def get_frags(self, seq_num):\n \"\"\"Get the Blocksat Packets sorted by fragment number\"\"\"\n return [x[1] for x in sorted(self.frag_map[seq_num]['frags'].items())]","function_tokens":["def","get_frags","(","self",",","seq_num",")",":","return","[","x","[","1","]","for","x","in","sorted","(","self",".","frag_map","[","seq_num","]","[","'frags'","]",".","items","(",")",")","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L264-L266"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.get_n_frags","parameters":"(self, seq_num)","argument_list":"","return_statement":"return len(self.frag_map[seq_num]['frags'].keys())","docstring":"Return the number of fragments corresponding to a sequence number","docstring_summary":"Return the number of fragments corresponding to a sequence number","docstring_tokens":["Return","the","number","of","fragments","corresponding","to","a","sequence","number"],"function":"def get_n_frags(self, seq_num):\n \"\"\"Return the number of fragments corresponding to a sequence number\"\"\"\n return len(self.frag_map[seq_num]['frags'].keys())","function_tokens":["def","get_n_frags","(","self",",","seq_num",")",":","return","len","(","self",".","frag_map","[","seq_num","]","[","'frags'","]",".","keys","(",")",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L268-L270"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.concat","parameters":"(self, seq_num, force=False)","argument_list":"","return_statement":"return bytes(self.frag_map[seq_num]['concat'])","docstring":"Concatenate all Blocksat Packet payloads composing an API message\n\n Args:\n seq_num : API message sequence number\n force : Force concatenation even if there are fragment gaps\n\n Returns:\n Bytes array with the concatenated payloads","docstring_summary":"Concatenate all Blocksat Packet payloads composing an API message","docstring_tokens":["Concatenate","all","Blocksat","Packet","payloads","composing","an","API","message"],"function":"def concat(self, seq_num, force=False):\n \"\"\"Concatenate all Blocksat Packet payloads composing an API message\n\n Args:\n seq_num : API message sequence number\n force : Force concatenation even if there are fragment gaps\n\n Returns:\n Bytes array with the concatenated payloads\n\n \"\"\"\n assert (seq_num in self.frag_map)\n\n # The caller should call this function only when it's known that the\n # message can be decoded\n if (not force and not self._check_gaps(seq_num)):\n raise RuntimeError(\"Gap found between message fragments\")\n\n if (not force and not self._check_ready(seq_num)):\n raise RuntimeError(\"Tried to decode while fragments are missing\")\n\n logger.debug(\"BlocksatPktHandler: Concatenated message with {} bytes \"\n \"(force: {})\".format(\n len(self.frag_map[seq_num]['concat']), force))\n\n # Take the concatenated message directly from the cache\n return bytes(self.frag_map[seq_num]['concat'])","function_tokens":["def","concat","(","self",",","seq_num",",","force","=","False",")",":","assert","(","seq_num","in","self",".","frag_map",")","# The caller should call this function only when it's known that the","# message can be decoded","if","(","not","force","and","not","self",".","_check_gaps","(","seq_num",")",")",":","raise","RuntimeError","(","\"Gap found between message fragments\"",")","if","(","not","force","and","not","self",".","_check_ready","(","seq_num",")",")",":","raise","RuntimeError","(","\"Tried to decode while fragments are missing\"",")","logger",".","debug","(","\"BlocksatPktHandler: Concatenated message with {} bytes \"","\"(force: {})\"",".","format","(","len","(","self",".","frag_map","[","seq_num","]","[","'concat'","]",")",",","force",")",")","# Take the concatenated message directly from the cache","return","bytes","(","self",".","frag_map","[","seq_num","]","[","'concat'","]",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L272-L298"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.split","parameters":"(self, data, seq_num, chan_num)","argument_list":"","return_statement":"","docstring":"Split data array into Blocksat Packet(s)\n\n An API message may be sent over multiple packet in case its length\n exceeds the maximum UDP payload. This function splits the message into\n packets and saves all the generated Blocksat Packets into the internal\n fragment map.\n\n Args:\n data : Bytes object containing the API message data\n seq_num : API Tx sequence number (`tx_seq_num` field)\n chan_num : API channel number","docstring_summary":"Split data array into Blocksat Packet(s)","docstring_tokens":["Split","data","array","into","Blocksat","Packet","(","s",")"],"function":"def split(self, data, seq_num, chan_num):\n \"\"\"Split data array into Blocksat Packet(s)\n\n An API message may be sent over multiple packet in case its length\n exceeds the maximum UDP payload. This function splits the message into\n packets and saves all the generated Blocksat Packets into the internal\n fragment map.\n\n Args:\n data : Bytes object containing the API message data\n seq_num : API Tx sequence number (`tx_seq_num` field)\n chan_num : API channel number\n\n \"\"\"\n assert (isinstance(data, bytes))\n n_frags = ceil(len(data) \/ MAX_PAYLOAD)\n\n logger.debug(\"BlocksatPktHandler: Message size: {:d} bytes\\t\"\n \"Fragments: {:d}\".format(len(data), n_frags))\n\n for i_frag in range(n_frags):\n # Is this the last_fragment?\n more_frags = (i_frag + 1) < n_frags\n\n # Byte range of the data to send on this Blocksat packet\n s_byte = i_frag * MAX_PAYLOAD # starting byte\n e_byte = (i_frag + 1) * MAX_PAYLOAD # ending byte\n\n # Packetize\n pkt = BlocksatPkt(seq_num, i_frag, chan_num, more_frags,\n data[s_byte:e_byte])\n\n # Add to fragment map\n self.append(pkt)","function_tokens":["def","split","(","self",",","data",",","seq_num",",","chan_num",")",":","assert","(","isinstance","(","data",",","bytes",")",")","n_frags","=","ceil","(","len","(","data",")","\/","MAX_PAYLOAD",")","logger",".","debug","(","\"BlocksatPktHandler: Message size: {:d} bytes\\t\"","\"Fragments: {:d}\"",".","format","(","len","(","data",")",",","n_frags",")",")","for","i_frag","in","range","(","n_frags",")",":","# Is this the last_fragment?","more_frags","=","(","i_frag","+","1",")","<","n_frags","# Byte range of the data to send on this Blocksat packet","s_byte","=","i_frag","*","MAX_PAYLOAD","# starting byte","e_byte","=","(","i_frag","+","1",")","*","MAX_PAYLOAD","# ending byte","# Packetize","pkt","=","BlocksatPkt","(","seq_num",",","i_frag",",","chan_num",",","more_frags",",","data","[","s_byte",":","e_byte","]",")","# Add to fragment map","self",".","append","(","pkt",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L300-L333"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/pkt.py","language":"python","identifier":"BlocksatPktHandler.clean","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Throw away old (timed-out) pending fragments","docstring_summary":"Throw away old (timed-out) pending fragments","docstring_tokens":["Throw","away","old","(","timed","-","out",")","pending","fragments"],"function":"def clean(self):\n \"\"\"Throw away old (timed-out) pending fragments\n \"\"\"\n # Find the timed-out messages\n timed_out = []\n t_now = time.time()\n for seq_num in self.frag_map:\n if (t_now - self.frag_map[seq_num]['t_last'] > self.timeout):\n timed_out.append(seq_num)\n\n # Delete the timed-out messages\n for seq_num in timed_out:\n logger.debug(\"BlocksatPktHandler: Delete Seq Num {} from fragment \"\n \"map\".format(seq_num))\n del self.frag_map[seq_num]","function_tokens":["def","clean","(","self",")",":","# Find the timed-out messages","timed_out","=","[","]","t_now","=","time",".","time","(",")","for","seq_num","in","self",".","frag_map",":","if","(","t_now","-","self",".","frag_map","[","seq_num","]","[","'t_last'","]",">","self",".","timeout",")",":","timed_out",".","append","(","seq_num",")","# Delete the timed-out messages","for","seq_num","in","timed_out",":","logger",".","debug","(","\"BlocksatPktHandler: Delete Seq Num {} from fragment \"","\"map\"",".","format","(","seq_num",")",")","del","self",".","frag_map","[","seq_num","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/pkt.py#L335-L349"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec.__init__","parameters":"(self, overhead=0.1)","argument_list":"","return_statement":"","docstring":"Constructor\n\n Args:\n overhead : Percentage of the FEC chunks to add as overhead\n (rounded up).","docstring_summary":"Constructor","docstring_tokens":["Constructor"],"function":"def __init__(self, overhead=0.1):\n \"\"\"Constructor\n\n Args:\n overhead : Percentage of the FEC chunks to add as overhead\n (rounded up).\n \"\"\"\n self.overhead = overhead","function_tokens":["def","__init__","(","self",",","overhead","=","0.1",")",":","self",".","overhead","=","overhead"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L71-L78"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec._encode_obj","parameters":"(self, data)","argument_list":"","return_statement":"return encoder.encode(chunks)","docstring":"Encode a single FEC object\n\n Args:\n data : Data to encode (bytes array)\n\n Note:\n Unlike method encode(), this method must take a data object that\n fits within 256 chunks with overhead so that it fits into a single\n FEC object. Furthermore, while encode() returns FEC packets,\n this method returns FEC chunks.\n\n Returns:\n List of FEC-encoded chunks.","docstring_summary":"Encode a single FEC object","docstring_tokens":["Encode","a","single","FEC","object"],"function":"def _encode_obj(self, data):\n \"\"\"Encode a single FEC object\n\n Args:\n data : Data to encode (bytes array)\n\n Note:\n Unlike method encode(), this method must take a data object that\n fits within 256 chunks with overhead so that it fits into a single\n FEC object. Furthermore, while encode() returns FEC packets,\n this method returns FEC chunks.\n\n Returns:\n List of FEC-encoded chunks.\n\n \"\"\"\n assert (isinstance(data, bytes))\n\n n_chunks = ceil(len(data) \/ CHUNK_SIZE)\n n_overhead_chunks = ceil(self.overhead * n_chunks)\n n_fec_chunks = n_chunks + n_overhead_chunks\n\n assert (n_fec_chunks <= MAX_FEC_CHUNKS)\n logger.debug(\"Original Chunks: {} \/ \"\n \"Overhead Chunks: {} \/ \"\n \"Total: {}\".format(n_chunks, n_overhead_chunks,\n n_fec_chunks))\n\n # Split the given data array into chunks\n chunks = []\n for i_chunk in range(n_chunks):\n # Byte range of the next chunk:\n s_byte = i_chunk * CHUNK_SIZE # starting byte\n e_byte = (i_chunk + 1) * CHUNK_SIZE # ending byte\n chunk = data[s_byte:e_byte]\n\n # The last chunk may need zero-padding\n if (i_chunk + 1 == n_chunks and len(chunk) < CHUNK_SIZE):\n chunk += bytes(CHUNK_SIZE - len(chunk))\n\n assert (len(chunk) == CHUNK_SIZE)\n chunks.append(chunk)\n\n # Generate the corresponding FEC chunks\n encoder = zfec.Encoder(n_chunks, n_fec_chunks)\n return encoder.encode(chunks)","function_tokens":["def","_encode_obj","(","self",",","data",")",":","assert","(","isinstance","(","data",",","bytes",")",")","n_chunks","=","ceil","(","len","(","data",")","\/","CHUNK_SIZE",")","n_overhead_chunks","=","ceil","(","self",".","overhead","*","n_chunks",")","n_fec_chunks","=","n_chunks","+","n_overhead_chunks","assert","(","n_fec_chunks","<=","MAX_FEC_CHUNKS",")","logger",".","debug","(","\"Original Chunks: {} \/ \"","\"Overhead Chunks: {} \/ \"","\"Total: {}\"",".","format","(","n_chunks",",","n_overhead_chunks",",","n_fec_chunks",")",")","# Split the given data array into chunks","chunks","=","[","]","for","i_chunk","in","range","(","n_chunks",")",":","# Byte range of the next chunk:","s_byte","=","i_chunk","*","CHUNK_SIZE","# starting byte","e_byte","=","(","i_chunk","+","1",")","*","CHUNK_SIZE","# ending byte","chunk","=","data","[","s_byte",":","e_byte","]","# The last chunk may need zero-padding","if","(","i_chunk","+","1","==","n_chunks","and","len","(","chunk",")","<","CHUNK_SIZE",")",":","chunk","+=","bytes","(","CHUNK_SIZE","-","len","(","chunk",")",")","assert","(","len","(","chunk",")","==","CHUNK_SIZE",")","chunks",".","append","(","chunk",")","# Generate the corresponding FEC chunks","encoder","=","zfec",".","Encoder","(","n_chunks",",","n_fec_chunks",")","return","encoder",".","encode","(","chunks",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L80-L125"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec.encode","parameters":"(self, data)","argument_list":"","return_statement":"return bytes(encoded_data)","docstring":"Encode message into FEC packets encompassing multiple FEC objects\n\n Generate the FEC packets (chunk + metadata) for the given message. If\n the message exceeds the capacity of one FEC object (up to 256 chunks),\n generate multiple FEC objects.\n\n Args:\n data : Data to encode (bytes array)\n\n Returns:\n Bytes array with all FEC packets serially (concatenated).","docstring_summary":"Encode message into FEC packets encompassing multiple FEC objects","docstring_tokens":["Encode","message","into","FEC","packets","encompassing","multiple","FEC","objects"],"function":"def encode(self, data):\n \"\"\"Encode message into FEC packets encompassing multiple FEC objects\n\n Generate the FEC packets (chunk + metadata) for the given message. If\n the message exceeds the capacity of one FEC object (up to 256 chunks),\n generate multiple FEC objects.\n\n Args:\n data : Data to encode (bytes array)\n\n Returns:\n Bytes array with all FEC packets serially (concatenated).\n\n \"\"\"\n assert (isinstance(data, bytes))\n\n # The FEC object should contain up to 256 chunks, including the\n # original (systematic) and the overhead chunks. The original data\n # object (to be encoded) should occupy up to \"256\/(1 + overhead)\"\n # chunks, whereas the overhead chunks should occupy \"(overhead *\n # 256)\/(1 + overhead)\" chunks. Also, the overhead cannot be greater\n # than 255, otherwise the original data has zero chunks per object.\n assert(self.overhead <= MAX_OVERHEAD), \\\n \"FEC overhead exceeds the maximum of {}\".format(MAX_OVERHEAD)\n\n max_obj_size = floor(MAX_FEC_CHUNKS \/ (1 + self.overhead)) * CHUNK_SIZE\n n_fec_objects = ceil(len(data) \/ max_obj_size)\n\n logger.debug(\"Message Size: {} \/ FEC Objects: {}\".format(\n len(data), n_fec_objects))\n\n # Generate the FEC packets from (potentially) multiple FEC objects\n fec_pkts = []\n for i_obj in range(n_fec_objects):\n s_byte = i_obj * max_obj_size # starting byte\n e_byte = (i_obj + 1) * max_obj_size # ending byte\n fec_object = data[s_byte:e_byte]\n\n logger.debug(\"FEC Object: {}\".format(i_obj))\n\n fec_chunks = self._encode_obj(fec_object)\n\n # FEC packets\n for i_chunk, chunk in enumerate(fec_chunks):\n metadata = struct.pack(HEADER_FORMAT, i_obj, n_fec_objects,\n i_chunk, len(fec_object))\n fec_pkts.append(metadata + chunk)\n\n # Concatenate all FEC packets to form a single encoded data\n # array. Concatenate them in random order so that the chunks from the\n # same object are not sent consecutively. This strategy is useful to\n # avoid error bursts.\n encoded_data = bytearray()\n random.shuffle(fec_pkts)\n for fec_pkt in fec_pkts:\n encoded_data += fec_pkt\n\n assert (len(encoded_data) % PKT_SIZE == 0)\n\n return bytes(encoded_data)","function_tokens":["def","encode","(","self",",","data",")",":","assert","(","isinstance","(","data",",","bytes",")",")","# The FEC object should contain up to 256 chunks, including the","# original (systematic) and the overhead chunks. The original data","# object (to be encoded) should occupy up to \"256\/(1 + overhead)\"","# chunks, whereas the overhead chunks should occupy \"(overhead *","# 256)\/(1 + overhead)\" chunks. Also, the overhead cannot be greater","# than 255, otherwise the original data has zero chunks per object.","assert","(","self",".","overhead","<=","MAX_OVERHEAD",")",",","\"FEC overhead exceeds the maximum of {}\"",".","format","(","MAX_OVERHEAD",")","max_obj_size","=","floor","(","MAX_FEC_CHUNKS","\/","(","1","+","self",".","overhead",")",")","*","CHUNK_SIZE","n_fec_objects","=","ceil","(","len","(","data",")","\/","max_obj_size",")","logger",".","debug","(","\"Message Size: {} \/ FEC Objects: {}\"",".","format","(","len","(","data",")",",","n_fec_objects",")",")","# Generate the FEC packets from (potentially) multiple FEC objects","fec_pkts","=","[","]","for","i_obj","in","range","(","n_fec_objects",")",":","s_byte","=","i_obj","*","max_obj_size","# starting byte","e_byte","=","(","i_obj","+","1",")","*","max_obj_size","# ending byte","fec_object","=","data","[","s_byte",":","e_byte","]","logger",".","debug","(","\"FEC Object: {}\"",".","format","(","i_obj",")",")","fec_chunks","=","self",".","_encode_obj","(","fec_object",")","# FEC packets","for","i_chunk",",","chunk","in","enumerate","(","fec_chunks",")",":","metadata","=","struct",".","pack","(","HEADER_FORMAT",",","i_obj",",","n_fec_objects",",","i_chunk",",","len","(","fec_object",")",")","fec_pkts",".","append","(","metadata","+","chunk",")","# Concatenate all FEC packets to form a single encoded data","# array. Concatenate them in random order so that the chunks from the","# same object are not sent consecutively. This strategy is useful to","# avoid error bursts.","encoded_data","=","bytearray","(",")","random",".","shuffle","(","fec_pkts",")","for","fec_pkt","in","fec_pkts",":","encoded_data","+=","fec_pkt","assert","(","len","(","encoded_data",")","%","PKT_SIZE","==","0",")","return","bytes","(","encoded_data",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L127-L186"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec._decode_obj","parameters":"(self, obj_len, chunks, chunk_ids)","argument_list":"","return_statement":"return decoded_obj[:obj_len]","docstring":"Decode a single FEC object\n\n Args:\n obj_len : Length of the original object encoded by the FEC\n object.\n chunks : List of FEC chunks.\n chunk_ids : List of ids associated with the list of FEC chunks.\n\n Note:\n Unlike method decode(), this method processes a single encoded FEC\n object.\n\n Returns:\n (bytearray) with the decoded (original) data object.","docstring_summary":"Decode a single FEC object","docstring_tokens":["Decode","a","single","FEC","object"],"function":"def _decode_obj(self, obj_len, chunks, chunk_ids):\n \"\"\"Decode a single FEC object\n\n Args:\n obj_len : Length of the original object encoded by the FEC\n object.\n chunks : List of FEC chunks.\n chunk_ids : List of ids associated with the list of FEC chunks.\n\n Note:\n Unlike method decode(), this method processes a single encoded FEC\n object.\n\n Returns:\n (bytearray) with the decoded (original) data object.\n\n \"\"\"\n # The original (uncoded) object must fit within the maximum number of\n # FEC chunks. Most of the time `obj_len` will be less than the\n # maximum. It only hits the maximum if the FEC overhead is set to zero.\n assert (obj_len <= (MAX_FEC_CHUNKS * CHUNK_SIZE))\n\n # Number of FEC chunks required to decode the original message:\n n_chunks = ceil(obj_len \/ CHUNK_SIZE)\n\n # FEC decoder\n decoder = zfec.Decoder(n_chunks, MAX_FEC_CHUNKS)\n # NOTE: The hard-coded \"MAX_FEC_CHUNKS\" represents the maximum number\n # of chunks that can be generated. The receiver does not know how many\n # chunks the sender really generated. Nevertheless, it does not need to\n # know, as long as it receives at least n_chunks (any combination of\n # n_chunks). The explanation for this requirement is that the FEC\n # scheme is a maximum distance separable (MDS) erasure code.\n\n # Decode using the minimum required number of FEC chunks\n decoded_chunks = decoder.decode(chunks[:n_chunks],\n chunk_ids[:n_chunks])\n\n # Concatenate the decoded chunks to form the original object\n decoded_obj = bytearray()\n for chunk in decoded_chunks:\n assert (len(chunk) == CHUNK_SIZE)\n decoded_obj += chunk\n\n # Remove any zero-padding that may have been applied to the last chunk:\n return decoded_obj[:obj_len]","function_tokens":["def","_decode_obj","(","self",",","obj_len",",","chunks",",","chunk_ids",")",":","# The original (uncoded) object must fit within the maximum number of","# FEC chunks. Most of the time `obj_len` will be less than the","# maximum. It only hits the maximum if the FEC overhead is set to zero.","assert","(","obj_len","<=","(","MAX_FEC_CHUNKS","*","CHUNK_SIZE",")",")","# Number of FEC chunks required to decode the original message:","n_chunks","=","ceil","(","obj_len","\/","CHUNK_SIZE",")","# FEC decoder","decoder","=","zfec",".","Decoder","(","n_chunks",",","MAX_FEC_CHUNKS",")","# NOTE: The hard-coded \"MAX_FEC_CHUNKS\" represents the maximum number","# of chunks that can be generated. The receiver does not know how many","# chunks the sender really generated. Nevertheless, it does not need to","# know, as long as it receives at least n_chunks (any combination of","# n_chunks). The explanation for this requirement is that the FEC","# scheme is a maximum distance separable (MDS) erasure code.","# Decode using the minimum required number of FEC chunks","decoded_chunks","=","decoder",".","decode","(","chunks","[",":","n_chunks","]",",","chunk_ids","[",":","n_chunks","]",")","# Concatenate the decoded chunks to form the original object","decoded_obj","=","bytearray","(",")","for","chunk","in","decoded_chunks",":","assert","(","len","(","chunk",")","==","CHUNK_SIZE",")","decoded_obj","+=","chunk","# Remove any zero-padding that may have been applied to the last chunk:","return","decoded_obj","[",":","obj_len","]"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L188-L233"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec._is_decodable","parameters":"(self, data)","argument_list":"","return_statement":"return True","docstring":"Check if the FEC-encoded data is decodable\n\n Args:\n data : FEC-encoded data, a bytes array with multiple FEC packets\n serially.\n\n Note: This is a faster processing tailored specifically to validate the\n given FEC-encoded data. Unlike method decode(), it does not make\n any expensive memory copying. The rationale is that the data will\n not be ready to be decoded most of the time. Hence, it is better to\n check if decodable separately than to try and decode it in one go.","docstring_summary":"Check if the FEC-encoded data is decodable","docstring_tokens":["Check","if","the","FEC","-","encoded","data","is","decodable"],"function":"def _is_decodable(self, data):\n \"\"\"Check if the FEC-encoded data is decodable\n\n Args:\n data : FEC-encoded data, a bytes array with multiple FEC packets\n serially.\n\n Note: This is a faster processing tailored specifically to validate the\n given FEC-encoded data. Unlike method decode(), it does not make\n any expensive memory copying. The rationale is that the data will\n not be ready to be decoded most of the time. Hence, it is better to\n check if decodable separately than to try and decode it in one go.\n\n \"\"\"\n\n # The encoded data must contain an integer number of FEC packets,\n # although it may not contain the full FEC-encoded object(s), given\n # that some parts of it may have been lost.\n if (len(data) % PKT_SIZE != 0):\n logger.debug(\"Not a properly formatted FEC-encoded object\")\n return False\n\n # Process each packet and create a map of FEC objects and chunks\n n_fec_pkts = len(data) \/\/ PKT_SIZE\n fec_map = {}\n n_fec_objects = None\n for i_fec_pkt in range(n_fec_pkts):\n # Byte range of the next header (don't process the payload here):\n s_byte = i_fec_pkt * PKT_SIZE # starting byte\n e_byte = s_byte + HEADER_LEN # ending byte\n\n # Unpack the metadata from the FEC header\n metadata = struct.unpack(HEADER_FORMAT, data[s_byte:e_byte])\n obj_id = metadata[0]\n chunk_id = metadata[2]\n obj_len = metadata[3]\n\n # Check if the chunk id is valid\n if (chunk_id >= MAX_FEC_CHUNKS):\n logger.debug(\"Invalid chunk id - likely not FEC-encoded\")\n return False\n\n # All packets of a FEC object should bring the same message length\n if (obj_id not in fec_map):\n fec_map[obj_id] = {'len': obj_len, 'n_chunks': 0}\n # NOTE: keep the count of chunks here (not the actual chunks).\n elif (obj_len != fec_map[obj_id]['len']):\n logger.debug(\"Inconsistent message length on FEC packets - \"\n \"likely not FEC-encoded\")\n return False\n\n # All FEC packets should bring the same metadata information\n # regarding the number of FEC objects\n if (n_fec_objects is None):\n n_fec_objects = metadata[1]\n elif (n_fec_objects != metadata[1]):\n logger.debug(\"Inconsistent number of FEC objects - \"\n \"likely not FEC-encoded\")\n return False\n\n # Increment the count of FEC chunks\n fec_map[obj_id]['n_chunks'] += 1\n\n # The decoder needs all the FEC objects\n if (n_fec_objects > len(fec_map)):\n logger.debug(\"Insufficient number of FEC objects\")\n return False\n\n # All FEC objects should contain enough FEC chunks\n ready = n_fec_objects * [False]\n for i_obj in range(n_fec_objects):\n n_chunks = ceil(fec_map[i_obj]['len'] \/ CHUNK_SIZE)\n ready[i_obj] = fec_map[i_obj]['n_chunks'] >= n_chunks\n\n if (not all(ready)):\n logger.debug(\"Insufficient number of FEC chunks\")\n return False\n\n logger.debug(\"Object decodable\")\n\n return True","function_tokens":["def","_is_decodable","(","self",",","data",")",":","# The encoded data must contain an integer number of FEC packets,","# although it may not contain the full FEC-encoded object(s), given","# that some parts of it may have been lost.","if","(","len","(","data",")","%","PKT_SIZE","!=","0",")",":","logger",".","debug","(","\"Not a properly formatted FEC-encoded object\"",")","return","False","# Process each packet and create a map of FEC objects and chunks","n_fec_pkts","=","len","(","data",")","\/\/","PKT_SIZE","fec_map","=","{","}","n_fec_objects","=","None","for","i_fec_pkt","in","range","(","n_fec_pkts",")",":","# Byte range of the next header (don't process the payload here):","s_byte","=","i_fec_pkt","*","PKT_SIZE","# starting byte","e_byte","=","s_byte","+","HEADER_LEN","# ending byte","# Unpack the metadata from the FEC header","metadata","=","struct",".","unpack","(","HEADER_FORMAT",",","data","[","s_byte",":","e_byte","]",")","obj_id","=","metadata","[","0","]","chunk_id","=","metadata","[","2","]","obj_len","=","metadata","[","3","]","# Check if the chunk id is valid","if","(","chunk_id",">=","MAX_FEC_CHUNKS",")",":","logger",".","debug","(","\"Invalid chunk id - likely not FEC-encoded\"",")","return","False","# All packets of a FEC object should bring the same message length","if","(","obj_id","not","in","fec_map",")",":","fec_map","[","obj_id","]","=","{","'len'",":","obj_len",",","'n_chunks'",":","0","}","# NOTE: keep the count of chunks here (not the actual chunks).","elif","(","obj_len","!=","fec_map","[","obj_id","]","[","'len'","]",")",":","logger",".","debug","(","\"Inconsistent message length on FEC packets - \"","\"likely not FEC-encoded\"",")","return","False","# All FEC packets should bring the same metadata information","# regarding the number of FEC objects","if","(","n_fec_objects","is","None",")",":","n_fec_objects","=","metadata","[","1","]","elif","(","n_fec_objects","!=","metadata","[","1","]",")",":","logger",".","debug","(","\"Inconsistent number of FEC objects - \"","\"likely not FEC-encoded\"",")","return","False","# Increment the count of FEC chunks","fec_map","[","obj_id","]","[","'n_chunks'","]","+=","1","# The decoder needs all the FEC objects","if","(","n_fec_objects",">","len","(","fec_map",")",")",":","logger",".","debug","(","\"Insufficient number of FEC objects\"",")","return","False","# All FEC objects should contain enough FEC chunks","ready","=","n_fec_objects","*","[","False","]","for","i_obj","in","range","(","n_fec_objects",")",":","n_chunks","=","ceil","(","fec_map","[","i_obj","]","[","'len'","]","\/","CHUNK_SIZE",")","ready","[","i_obj","]","=","fec_map","[","i_obj","]","[","'n_chunks'","]",">=","n_chunks","if","(","not","all","(","ready",")",")",":","logger",".","debug","(","\"Insufficient number of FEC chunks\"",")","return","False","logger",".","debug","(","\"Object decodable\"",")","return","True"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L235-L315"} {"nwo":"Blockstream\/satellite","sha":"7948ba8f568718008529951c81625ebe5a759bdf","path":"blocksatcli\/api\/fec.py","language":"python","identifier":"Fec.decode","parameters":"(self, data)","argument_list":"","return_statement":"return bytes(decoded_data)","docstring":"Decode a sequence of FEC packets spanning multiple FEC objects\n\n Args:\n data : FEC-encoded data, a bytes array with multiple FEC packets\n serially.\n\n Returns:\n False if decoding fails. Otherwise, a bytes array with the decoded\n data (i.e., the original message).","docstring_summary":"Decode a sequence of FEC packets spanning multiple FEC objects","docstring_tokens":["Decode","a","sequence","of","FEC","packets","spanning","multiple","FEC","objects"],"function":"def decode(self, data):\n \"\"\"Decode a sequence of FEC packets spanning multiple FEC objects\n\n Args:\n data : FEC-encoded data, a bytes array with multiple FEC packets\n serially.\n\n Returns:\n False if decoding fails. Otherwise, a bytes array with the decoded\n data (i.e., the original message).\n\n \"\"\"\n\n # Check if the given FEC-encoded can decoded before anything to avoid\n # the more expensive message decoding that follows.\n if (not self._is_decodable(data)):\n return False\n\n # Process each packet and create a map of FEC objects and chunks\n n_fec_pkts = len(data) \/\/ PKT_SIZE\n fec_map = {}\n n_fec_objects = None\n for i_fec_pkt in range(n_fec_pkts):\n # Byte range of the next FEC packet:\n s_byte = i_fec_pkt * PKT_SIZE # starting byte\n e_byte = (i_fec_pkt + 1) * PKT_SIZE # ending byte\n fec_pkt = data[s_byte:e_byte]\n\n # Unpack the metadata from the FEC header\n obj_id, n_fec_objects, chunk_id, obj_len = struct.unpack(\n HEADER_FORMAT, fec_pkt[:HEADER_LEN])\n\n # Save the FEC object length and the FEC chunk\n if (obj_id not in fec_map):\n fec_map[obj_id] = {'len': obj_len, 'chunks': {}}\n\n fec_map[obj_id]['chunks'][chunk_id] = fec_pkt[HEADER_LEN:]\n\n logger.debug(\"Processed chunks: {} \/ Processed objects: {}\".format(\n n_fec_pkts, len(fec_map)))\n\n # Decode multiple objects and concatenate the decoded data\n decoded_data = bytearray()\n for i_obj in range(n_fec_objects):\n decoded_data += self._decode_obj(\n fec_map[i_obj]['len'], list(fec_map[i_obj]['chunks'].values()),\n list(fec_map[i_obj]['chunks'].keys()))\n\n return bytes(decoded_data)","function_tokens":["def","decode","(","self",",","data",")",":","# Check if the given FEC-encoded can decoded before anything to avoid","# the more expensive message decoding that follows.","if","(","not","self",".","_is_decodable","(","data",")",")",":","return","False","# Process each packet and create a map of FEC objects and chunks","n_fec_pkts","=","len","(","data",")","\/\/","PKT_SIZE","fec_map","=","{","}","n_fec_objects","=","None","for","i_fec_pkt","in","range","(","n_fec_pkts",")",":","# Byte range of the next FEC packet:","s_byte","=","i_fec_pkt","*","PKT_SIZE","# starting byte","e_byte","=","(","i_fec_pkt","+","1",")","*","PKT_SIZE","# ending byte","fec_pkt","=","data","[","s_byte",":","e_byte","]","# Unpack the metadata from the FEC header","obj_id",",","n_fec_objects",",","chunk_id",",","obj_len","=","struct",".","unpack","(","HEADER_FORMAT",",","fec_pkt","[",":","HEADER_LEN","]",")","# Save the FEC object length and the FEC chunk","if","(","obj_id","not","in","fec_map",")",":","fec_map","[","obj_id","]","=","{","'len'",":","obj_len",",","'chunks'",":","{","}","}","fec_map","[","obj_id","]","[","'chunks'","]","[","chunk_id","]","=","fec_pkt","[","HEADER_LEN",":","]","logger",".","debug","(","\"Processed chunks: {} \/ Processed objects: {}\"",".","format","(","n_fec_pkts",",","len","(","fec_map",")",")",")","# Decode multiple objects and concatenate the decoded data","decoded_data","=","bytearray","(",")","for","i_obj","in","range","(","n_fec_objects",")",":","decoded_data","+=","self",".","_decode_obj","(","fec_map","[","i_obj","]","[","'len'","]",",","list","(","fec_map","[","i_obj","]","[","'chunks'","]",".","values","(",")",")",",","list","(","fec_map","[","i_obj","]","[","'chunks'","]",".","keys","(",")",")",")","return","bytes","(","decoded_data",")"],"url":"https:\/\/github.com\/Blockstream\/satellite\/blob\/7948ba8f568718008529951c81625ebe5a759bdf\/blocksatcli\/api\/fec.py#L317-L365"}