<commit_before>import asyncio
import collections
import datetime
import hashlib
import random
import re
import urllib.parse

import discord
from discord.ext import commands

import ao3

import html2text

class Misc:
    @commands.command()
    async def highfive(self, ctx: commands.Context):
        """
        Give Yutu a high-five
        """
        await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))

    @commands.command()
    async def rate(self, ctx: commands.Context, *, subject):
        """
        Ask Yutu to rate a thing
        """
        subject = await commands.clean_content().convert(ctx, subject)
        hasher = hashlib.sha256()
        hasher.update(subject.lower().encode("UTF-8"))
        rate = int(hasher.hexdigest(), 16) % 1001
        await ctx.e_say("**{me}** gives **{item}** a rating of **{rate}/100**",
                        item=subject,
                        rate=rate/10.0)

    @commands.command()
    async def numerology(self, ctx: commands.Context, *, subject):
        """
        Ask Yutu to do a numerology calculation on something
        """
        subject = await commands.clean_content().convert(ctx, subject)
        post = "```\nCalculating numerological result for \"{}\"\n\n".format(subject)
        chars = [c.upper() for c in subject if c.isalpha()]
        post += " + ".join(chars)
        post += "\n\n"
        vals = [((ord(c)-65) % 9) + 1 for c in chars]
        post += " + ".join([str(i) for i in vals])
        s = sum(vals)
        post += " = {}\n\n".format(s)
        while s > 9 and (s > 40 or s % 11 != 0):
            digits = [int(c) for c in str(s)]
            post += " + ".join([str(i) for i in digits])
            s = sum(digits)
            post += " = {}\n\n".format(s)
        post += "\n"
        post += {1: "1 – Initiator action, pioneering, leading, independent, attaining, individualistic",
                 2: "2 – Cooperation, adaptability, consideration of others, partnering, mediating",
                 3: "3 – Expression, verbalization, socialization, the arts, the joy of living",
                 4: "4 – Values foundation, order, service, struggle against limits, steady growth",
                 5: "5 – Expansiveness, visionary, adventure, the constructive use of freedom",
                 6: "6 – Responsibility, protection, nurturing, community, balance, sympathy",
                 7: "7 – Analysis, understanding, knowledge, awareness, studious, meditating",
                 8: "8 – Practical endeavors, status oriented, power-seeking, high-material goals",
                 9: "9 – Humanitarian, giving nature, selflessness, obligations, creative expression",
                 11: "11 – Higher spiritual plane, intuitive, illumination, idealist, a dreamer",
                 22: "22 – The Master Builder, large endeavors, powerful force, leadership",
                 33: "33 - The Master Teacher, humanitarian, usually only found in Big Names"}[s]
        post += "```"
        await ctx.send(content=post)

    @commands.command()
    async def commend(self, ctx: commands.Context, user: discord.Member, *, reason):
        """
        Commend a user, with optional reason
        """
        reason = await commands.clean_content().convert(ctx, reason)
        embed = discord.Embed()
        if reason:
            embed.description = (":trophy::military_medal: "
                                 "**{0.display_name}** commends **{1.display_name}**"
                                 " :military_medal::trophy:\n"
                                 "for {2}").format(ctx.author, user, reason)
        else:
            embed.description = (":trophy::military_medal: "
                                 "**{0.display_name}** commends **{1.display_name}**"
                                 " :military_medal::trophy:").format(ctx.author, user)
        await ctx.send(embed=embed)

    @commands.command()
    async def vote(self, ctx: commands.Context, *, msg):
        """
        Start a vote on something.
        """
        msg = await commands.clean_content().convert(ctx, msg)
        post = await ctx.send(content=":inbox_tray: A vote has been started by **{0.display_name}**".format(ctx.author),
                              embed=discord.Embed(title=msg))
        await post.add_reaction("👍")
        await post.add_reaction("🤷")
        await post.add_reaction("👎")

    @commands.command()
    async def f(self, ctx: commands.Context):
        """
        Pay your respects
        """
        await ctx.send(content="**{0}** has paid {0.pronouns.dep_poss} respects {1}".format(
            ctx.author,
            random.choice([':heart:',
                           ':yellow_heart:',
                           ':blue_heart:',
                           ':purple_heart:',
                           ':green_heart:'])))

    @commands.command()
    async def poll(self, ctx: commands.Context):
        """
        Interactivly create a poll
        """
        def check(msg):
            return msg.author == ctx.author and msg.channel == ctx.channel

        posts_to_del = [ctx.message, await ctx.send("Please describe the poll topic.")]

        try:
            post = await ctx.bot.wait_for("message", check=check, timeout=600)
            posts_to_del.append(post)
            topic = post.content
        except asyncio.TimeoutError:
            await ctx.send("Aborting, timed out.", delete_after=30)
            await ctx.channel.delete_messages(posts_to_del)
            return

        numerals = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟']
        options = []
        for n in numerals:
            posts_to_del.append(await ctx.send("Please enter a poll option (max 10) or \"STOP\" to finish."))
            try:
                post = await ctx.bot.wait_for("message", check=check, timeout=600)
                posts_to_del.append(post)
                if post.content == "STOP":
                    break
                options.append((n, post.content))
            except asyncio.TimeoutError:
                await ctx.send("Aborting, timed out.", delete_after=30)
                await ctx.channel.delete_messages(posts_to_del)
                return
        await ctx.channel.delete_messages(posts_to_del)
        post = discord.Embed(description="{}\n{}".format(topic,
                                                         "\n".join(["{}: {}".format(n, option)
                                                                    for n, option in options])))
        vote = await ctx.send(content=":inbox_tray: A vote has been started by **{}**".format(ctx.author),
                              embed=post)
        for n, _ in options:
            await vote.add_reaction(n)

    @commands.command()
    async def quote(self, ctx: commands.Context, user: discord.Member, *, identifier=None):
        """
        Quote a user.

        Sends quotes to http://scarlatinashenanigans.tumblr.com
        It can only quote in the last 200 messages on channel.
        If you don't supply an identifier it will quote the users last message block.
        If you do it will quote the rest of the first block
        that starts with a message containing that text, case insensitive.
        """
        quote_user = user.name
        async for message in ctx.channel.history(limit=200, before=ctx.message):
            if message.author == user:
                if identifier is not None:
                    if identifier.lower() in message.clean_content.lower():
                        quote_text = message.clean_content
                        async for msg in ctx.channel.history(limit=100, after=message, reverse=True):
                            if msg.id == ctx.message.id or msg.author != user:
                                break
                            quote_text = quote_text + '\n' + msg.clean_content
                        break
                else:
                    quote_text = message.clean_content
                    async for msg in ctx.channel.history(limit=100, before=message):
                        if msg.author != user:
                            break
                        quote_text = msg.clean_content + '\n' + quote_text
                    break
        else:
            await ctx.send("I'm sorry, I can't find that.")
            return
        print(quote_text)
        ctx.bot.tumblr.create_quote("scarlatinashenanigans.tumblr.com",
                                    state="draft",
                                    quote=quote_text,
                                    source=quote_user)
        await ctx.send("Quoting {0.mention}:\n\"{1}\"".format(user, quote_text))

    @commands.command(hidden=True)
    async def gayformurph(self, ctx: commands.Context):
        murph = ctx.bot.get_user(184073774822326273)
        await ctx.send("{0.mention} is so very gay for {1.mention}.".format(ctx.author, murph))

    @commands.command(hidden=True)
    async def verygayformurph(self, ctx: commands.Context):
        murph = ctx.bot.get_user(184073774822326273)
        await ctx.send("Even if stranded on Themyscira, {0.mention} would swim the ocean to find {1.mention}.".format(ctx.author, murph))

    def format_ao3(self, work):
        def make_link(elm):
            return "[{}]({})".format(elm,
                                     elm.url.replace("(", "%28").replace(")", "%29"))

        def make_str(lst):
            return [str(elm) for elm in lst]

        def make_links(lst):
            return [make_link(elm) for elm in lst]

        disp = discord.Embed()
        disp.title = work.title
        disp.url = work.url
        disp.colour = 9437184
        disp.timestamp = datetime.datetime.combine(work.published, datetime.time())
        infodict = collections.OrderedDict()
        infodict["Rating"] = ", ".join(make_str(work.rating))
        infodict["Archive Warnings"] = "No Archive Warnings Apply" if not work.warnings else ", ".join(
            make_str(work.warnings))
        infodict["Category"] = ", ".join(make_str(work.category))
        if work.fandoms:
            infodict['Fandom'] = ", ".join(make_links(work.fandoms))
        infodict['Language'] = work.language
        if work.series:
            infodict['Series'] = "Part {} of {}".format(work.series_idx, make_link(work.series))
        infodict['Stats'] = "Words: {} Hits: {} Kudos: {} Chapters: {}/{}".format(work.words,
                                                                                work.hits,
                                                                                work.kudos,
                                                                                work.published_chapters,
                                                                                "?"
                                                                                if work.total_chapters is None else
                                                                                work.total_chapters)
        info = "\n".join(["**{}**: {}".format(k, v)
                          for k, v
                          in infodict.items()])
        disp.description = """by {}\n\n{}""".format(", ".join(make_links(work.authors)),
                                                    info)
        total_len = len(disp.description)
        if work.relationship:
            val = ", ".join(make_links(work.relationship))
            if len(val) > 1024:
                val = ", ".join(make_str(work.relationship))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Relationships",
                           value=val,
                           inline=False)
        if work.characters:
            val = ", ".join(make_links(work.characters))
            if len(val) > 1024:
                val = ", ".join(make_str(work.characters))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Characters",
                           value=val,
                           inline=False)
        if work.additional_tags:
            val = ", ".join(make_links(work.additional_tags))
            if len(val) > 1024:
                val = ", ".join(make_str(work.additional_tags))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Additional Tags",
                           value=val,
                           inline=False)
        val = html2text.html2text(work.summary)
        if len(val) > 1024:
            val = val[:1021] + "..."
        if total_len + len(val) > 6000:
            if total_len < 5997:
                val = val[:5997-total_len] + "..."
            else:
                return discord.Embed(description=":( I tried but that fic has too much info.")
        disp.add_field(name="Description",
                       value=val,
                       inline=False)
        return disp

    @commands.command()
    async def ao3(self, ctx: commands.Context, msg: str):
        """
        Attach a preview of an Ao3 Work
        """

        try:
            wid = int(msg)
        except ValueError:
            mtch = re.match("^https?://(?:www.)?archiveofourown.org/works/(\d*).*$", msg)
            if mtch is None:
                await ctx.send("Error: Please provide either a workID or a URL")
                return
            wid = int(mtch.group(1))
        async with ctx.typing():
            api = ao3.AO3()
            try:
                work = api.work(id=wid)
            except:
                await ctx.send("Error: Can't find a work with that ID/URL")
                raise
                #return
            disp = self.format_ao3(work)
            await ctx.send(embed=disp)

    @commands.command()
    async def ctof(self, ctx: commands.Context, temp: float):
        """
        Convert celcius to farenheit
        """
        await ctx.send(content="{:0.2f}C == {:0.2f}F".format(temp, temp*1.8 + 32))

    @commands.command()
    async def ftoc(self, ctx: commands.Context, temp: float):
        """
        Convert farenheit to celcius
        """
        await ctx.send(content="{:0.2f}F == {:0.2f}C".format(temp, ((temp - 32)*5)/9))

    @commands.command()
    async def nickhist(self, ctx: commands.Context):
        """
        Query who last changed your nick
        """
        async for entry in ctx.guild.audit_logs(action=discord.AuditLogAction.member_update):
            if entry.target == ctx.author and entry.before.nick != entry.after.nick:
                if entry.before.nick is None:
                    await ctx.send(content="**{}** set your nick at {} to **{}**.".format(
                        entry.user,
                        entry.created_at,
                        entry.after.nick
                    ))
                else:
                    if entry.after.nick is None:
                        await ctx.send(content="**{}** cleared your nick at {} from **{}**.".format(
                            entry.user,
                            entry.created_at,
                            entry.before.nick
                        ))
                    else:
                        await ctx.send(content="**{}** changed your nick at {} from **{}** to **{}**.".format(
                            entry.user,
                            entry.created_at,
                            entry.before.nick,
                            entry.after.nick
                        ))
                break
        else:
            await ctx.send(content="Sorry, it doesn't look like anyone has changed your nick recently.")
<commit_msg>Even more logging<commit_after>import asyncio
import collections
import datetime
import hashlib
import random
import re
import urllib.parse
import traceback

import discord
from discord.ext import commands

import ao3

import html2text

class Misc:
    @commands.command()
    async def highfive(self, ctx: commands.Context):
        """
        Give Yutu a high-five
        """
        await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))

    @commands.command()
    async def rate(self, ctx: commands.Context, *, subject):
        """
        Ask Yutu to rate a thing
        """
        subject = await commands.clean_content().convert(ctx, subject)
        hasher = hashlib.sha256()
        hasher.update(subject.lower().encode("UTF-8"))
        rate = int(hasher.hexdigest(), 16) % 1001
        await ctx.e_say("**{me}** gives **{item}** a rating of **{rate}/100**",
                        item=subject,
                        rate=rate/10.0)

    @commands.command()
    async def numerology(self, ctx: commands.Context, *, subject):
        """
        Ask Yutu to do a numerology calculation on something
        """
        subject = await commands.clean_content().convert(ctx, subject)
        post = "```\nCalculating numerological result for \"{}\"\n\n".format(subject)
        chars = [c.upper() for c in subject if c.isalpha()]
        post += " + ".join(chars)
        post += "\n\n"
        vals = [((ord(c)-65) % 9) + 1 for c in chars]
        post += " + ".join([str(i) for i in vals])
        s = sum(vals)
        post += " = {}\n\n".format(s)
        while s > 9 and (s > 40 or s % 11 != 0):
            digits = [int(c) for c in str(s)]
            post += " + ".join([str(i) for i in digits])
            s = sum(digits)
            post += " = {}\n\n".format(s)
        post += "\n"
        post += {1: "1 – Initiator action, pioneering, leading, independent, attaining, individualistic",
                 2: "2 – Cooperation, adaptability, consideration of others, partnering, mediating",
                 3: "3 – Expression, verbalization, socialization, the arts, the joy of living",
                 4: "4 – Values foundation, order, service, struggle against limits, steady growth",
                 5: "5 – Expansiveness, visionary, adventure, the constructive use of freedom",
                 6: "6 – Responsibility, protection, nurturing, community, balance, sympathy",
                 7: "7 – Analysis, understanding, knowledge, awareness, studious, meditating",
                 8: "8 – Practical endeavors, status oriented, power-seeking, high-material goals",
                 9: "9 – Humanitarian, giving nature, selflessness, obligations, creative expression",
                 11: "11 – Higher spiritual plane, intuitive, illumination, idealist, a dreamer",
                 22: "22 – The Master Builder, large endeavors, powerful force, leadership",
                 33: "33 - The Master Teacher, humanitarian, usually only found in Big Names"}[s]
        post += "```"
        await ctx.send(content=post)

    @commands.command()
    async def commend(self, ctx: commands.Context, user: discord.Member, *, reason):
        """
        Commend a user, with optional reason
        """
        reason = await commands.clean_content().convert(ctx, reason)
        embed = discord.Embed()
        if reason:
            embed.description = (":trophy::military_medal: "
                                 "**{0.display_name}** commends **{1.display_name}**"
                                 " :military_medal::trophy:\n"
                                 "for {2}").format(ctx.author, user, reason)
        else:
            embed.description = (":trophy::military_medal: "
                                 "**{0.display_name}** commends **{1.display_name}**"
                                 " :military_medal::trophy:").format(ctx.author, user)
        await ctx.send(embed=embed)

    @commands.command()
    async def vote(self, ctx: commands.Context, *, msg):
        """
        Start a vote on something.
        """
        msg = await commands.clean_content().convert(ctx, msg)
        post = await ctx.send(content=":inbox_tray: A vote has been started by **{0.display_name}**".format(ctx.author),
                              embed=discord.Embed(title=msg))
        await post.add_reaction("👍")
        await post.add_reaction("🤷")
        await post.add_reaction("👎")

    @commands.command()
    async def f(self, ctx: commands.Context):
        """
        Pay your respects
        """
        await ctx.send(content="**{0}** has paid {0.pronouns.dep_poss} respects {1}".format(
            ctx.author,
            random.choice([':heart:',
                           ':yellow_heart:',
                           ':blue_heart:',
                           ':purple_heart:',
                           ':green_heart:'])))

    @commands.command()
    async def poll(self, ctx: commands.Context):
        """
        Interactivly create a poll
        """
        def check(msg):
            return msg.author == ctx.author and msg.channel == ctx.channel

        posts_to_del = [ctx.message, await ctx.send("Please describe the poll topic.")]

        try:
            post = await ctx.bot.wait_for("message", check=check, timeout=600)
            posts_to_del.append(post)
            topic = post.content
        except asyncio.TimeoutError:
            await ctx.send("Aborting, timed out.", delete_after=30)
            await ctx.channel.delete_messages(posts_to_del)
            return

        numerals = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟']
        options = []
        for n in numerals:
            posts_to_del.append(await ctx.send("Please enter a poll option (max 10) or \"STOP\" to finish."))
            try:
                post = await ctx.bot.wait_for("message", check=check, timeout=600)
                posts_to_del.append(post)
                if post.content == "STOP":
                    break
                options.append((n, post.content))
            except asyncio.TimeoutError:
                await ctx.send("Aborting, timed out.", delete_after=30)
                await ctx.channel.delete_messages(posts_to_del)
                return
        await ctx.channel.delete_messages(posts_to_del)
        post = discord.Embed(description="{}\n{}".format(topic,
                                                         "\n".join(["{}: {}".format(n, option)
                                                                    for n, option in options])))
        vote = await ctx.send(content=":inbox_tray: A vote has been started by **{}**".format(ctx.author),
                              embed=post)
        for n, _ in options:
            await vote.add_reaction(n)

    @commands.command()
    async def quote(self, ctx: commands.Context, user: discord.Member, *, identifier=None):
        """
        Quote a user.

        Sends quotes to http://scarlatinashenanigans.tumblr.com
        It can only quote in the last 200 messages on channel.
        If you don't supply an identifier it will quote the users last message block.
        If you do it will quote the rest of the first block
        that starts with a message containing that text, case insensitive.
        """
        quote_user = user.name
        async for message in ctx.channel.history(limit=200, before=ctx.message):
            if message.author == user:
                if identifier is not None:
                    if identifier.lower() in message.clean_content.lower():
                        quote_text = message.clean_content
                        async for msg in ctx.channel.history(limit=100, after=message, reverse=True):
                            if msg.id == ctx.message.id or msg.author != user:
                                break
                            quote_text = quote_text + '\n' + msg.clean_content
                        break
                else:
                    quote_text = message.clean_content
                    async for msg in ctx.channel.history(limit=100, before=message):
                        if msg.author != user:
                            break
                        quote_text = msg.clean_content + '\n' + quote_text
                    break
        else:
            await ctx.send("I'm sorry, I can't find that.")
            return
        print(quote_text)
        ctx.bot.tumblr.create_quote("scarlatinashenanigans.tumblr.com",
                                    state="draft",
                                    quote=quote_text,
                                    source=quote_user)
        await ctx.send("Quoting {0.mention}:\n\"{1}\"".format(user, quote_text))

    @commands.command(hidden=True)
    async def gayformurph(self, ctx: commands.Context):
        murph = ctx.bot.get_user(184073774822326273)
        await ctx.send("{0.mention} is so very gay for {1.mention}.".format(ctx.author, murph))

    @commands.command(hidden=True)
    async def verygayformurph(self, ctx: commands.Context):
        murph = ctx.bot.get_user(184073774822326273)
        await ctx.send("Even if stranded on Themyscira, {0.mention} would swim the ocean to find {1.mention}.".format(ctx.author, murph))

    def format_ao3(self, work):
        def make_link(elm):
            return "[{}]({})".format(elm,
                                     elm.url.replace("(", "%28").replace(")", "%29"))

        def make_str(lst):
            return [str(elm) for elm in lst]

        def make_links(lst):
            return [make_link(elm) for elm in lst]

        disp = discord.Embed()
        disp.title = work.title
        disp.url = work.url
        disp.colour = 9437184
        disp.timestamp = datetime.datetime.combine(work.published, datetime.time())
        infodict = collections.OrderedDict()
        infodict["Rating"] = ", ".join(make_str(work.rating))
        infodict["Archive Warnings"] = "No Archive Warnings Apply" if not work.warnings else ", ".join(
            make_str(work.warnings))
        infodict["Category"] = ", ".join(make_str(work.category))
        if work.fandoms:
            infodict['Fandom'] = ", ".join(make_links(work.fandoms))
        infodict['Language'] = work.language
        if work.series:
            infodict['Series'] = "Part {} of {}".format(work.series_idx, make_link(work.series))
        infodict['Stats'] = "Words: {} Hits: {} Kudos: {} Chapters: {}/{}".format(work.words,
                                                                                work.hits,
                                                                                work.kudos,
                                                                                work.published_chapters,
                                                                                "?"
                                                                                if work.total_chapters is None else
                                                                                work.total_chapters)
        info = "\n".join(["**{}**: {}".format(k, v)
                          for k, v
                          in infodict.items()])
        disp.description = """by {}\n\n{}""".format(", ".join(make_links(work.authors)),
                                                    info)
        total_len = len(disp.description)
        if work.relationship:
            val = ", ".join(make_links(work.relationship))
            if len(val) > 1024:
                val = ", ".join(make_str(work.relationship))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Relationships",
                           value=val,
                           inline=False)
        if work.characters:
            val = ", ".join(make_links(work.characters))
            if len(val) > 1024:
                val = ", ".join(make_str(work.characters))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Characters",
                           value=val,
                           inline=False)
        if work.additional_tags:
            val = ", ".join(make_links(work.additional_tags))
            if len(val) > 1024:
                val = ", ".join(make_str(work.additional_tags))
            if len(val) > 1024:
                val = val[:1021] + "..."
            total_len += len(val)
            disp.add_field(name="Additional Tags",
                           value=val,
                           inline=False)
        val = html2text.html2text(work.summary)
        if len(val) > 1024:
            val = val[:1021] + "..."
        if total_len + len(val) > 6000:
            if total_len < 5997:
                val = val[:5997-total_len] + "..."
            else:
                return discord.Embed(description=":( I tried but that fic has too much info.")
        disp.add_field(name="Description",
                       value=val,
                       inline=False)
        return disp

    @commands.command()
    async def ao3(self, ctx: commands.Context, msg: str):
        """
        Attach a preview of an Ao3 Work
        """

        try:
            wid = int(msg)
        except ValueError:
            mtch = re.match("^https?://(?:www.)?archiveofourown.org/works/(\d*).*$", msg)
            if mtch is None:
                await ctx.send("Error: Please provide either a workID or a URL")
                return
            wid = int(mtch.group(1))
        async with ctx.typing():
            api = ao3.AO3()
            try:
                work = api.work(id=wid)
            except Exception as ex:
                await ctx.send("Error: Can't find a work with that ID/URL")
                await ctx.bot.pm_owner(content="".join(traceback.format_exception(None, ex, None)))
                return
            disp = self.format_ao3(work)
            await ctx.send(embed=disp)

    @commands.command()
    async def ctof(self, ctx: commands.Context, temp: float):
        """
        Convert celcius to farenheit
        """
        await ctx.send(content="{:0.2f}C == {:0.2f}F".format(temp, temp*1.8 + 32))

    @commands.command()
    async def ftoc(self, ctx: commands.Context, temp: float):
        """
        Convert farenheit to celcius
        """
        await ctx.send(content="{:0.2f}F == {:0.2f}C".format(temp, ((temp - 32)*5)/9))

    @commands.command()
    async def nickhist(self, ctx: commands.Context):
        """
        Query who last changed your nick
        """
        async for entry in ctx.guild.audit_logs(action=discord.AuditLogAction.member_update):
            if entry.target == ctx.author and entry.before.nick != entry.after.nick:
                if entry.before.nick is None:
                    await ctx.send(content="**{}** set your nick at {} to **{}**.".format(
                        entry.user,
                        entry.created_at,
                        entry.after.nick
                    ))
                else:
                    if entry.after.nick is None:
                        await ctx.send(content="**{}** cleared your nick at {} from **{}**.".format(
                            entry.user,
                            entry.created_at,
                            entry.before.nick
                        ))
                    else:
                        await ctx.send(content="**{}** changed your nick at {} from **{}** to **{}**.".format(
                            entry.user,
                            entry.created_at,
                            entry.before.nick,
                            entry.after.nick
                        ))
                break
        else:
            await ctx.send(content="Sorry, it doesn't look like anyone has changed your nick recently.")
<|endoftext|>


<commit_before>'''
The crypt module manages all of the cryptography functions for minions and
masters, encrypting and decrypting payloads, preparing messages, and
authenticating peers
'''

# Import python libs
import os
import sys
import hmac
import hashlib
import logging

# Import third party libs
from M2Crypto import RSA
from Crypto.Cipher import AES

# Import salt libs
import salt.utils
import salt.payload
import salt.utils.verify
import salt.version
from salt.exceptions import (
    AuthenticationError, SaltClientError, SaltReqTimeoutError
)

log = logging.getLogger(__name__)

def dropfile(cachedir):
    '''
    Set an aes dropfile to update the publish session key
    '''
    dfn = os.path.join(cachedir, '.dfn')
    aes = Crypticle.generate_key_string()
    mask = os.umask(191)
    with open(dfn, 'w+') as fp_:
        fp_.write(aes)
    os.umask(mask)

def gen_keys(keydir, keyname, keysize, user=None):
    '''
    Generate a keypair for use with salt
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)

    gen = RSA.gen_key(keysize, 65537, callback=lambda x, y, z: None)
    cumask = os.umask(191)
    gen.save_key(priv, None)
    os.umask(cumask)
    gen.save_pub_key(pub)
    os.chmod(priv, 256)
    if user:
        try:
            import pwd
            uid = pwd.getpwnam(user).pw_uid
            os.chown(priv, uid, -1)
            os.chown(pub, uid, -1)
        except (KeyError, ImportError, OSError):
            # The specified user was not found, allow the backup systems to
            # report the error
            pass
    return priv

class MasterKeys(dict):
    '''
    The Master Keys class is used to manage the public key pair used for
    authentication by the master.
    '''
    def __init__(self, opts):
        super(MasterKeys, self).__init__()
        self.opts = opts
        self.pub_path = os.path.join(self.opts['pki_dir'], 'master.pub')
        self.rsa_path = os.path.join(self.opts['pki_dir'], 'master.pem')
        self.key = self.__get_keys()
        self.token = self.__gen_token()

    def __get_keys(self):
        '''
        Returns a key objects for the master
        '''
        if os.path.exists(self.rsa_path):
            key = RSA.load_key(self.rsa_path)
            log.debug('Loaded master key: {0}'.format(self.rsa_path))
        else:
            log.info('Generating keys: {0}'.format(self.opts['pki_dir']))
            gen_keys(
                    self.opts['pki_dir'],
                    'master',
                    4096,
                    self.opts.get('user'))
            key = RSA.load_key(self.rsa_path)
        return key

    def __gen_token(self):
        '''
        Generate the authentication token
        '''
        return self.key.private_encrypt('salty bacon', 5)

    def get_pub_str(self):
        '''
        Return the string representation of the public key
        '''
        if not os.path.isfile(self.pub_path):
            key = self.__get_keys()
            key.save_pub_key(self.pub_path)
        return salt.utils.fopen(self.pub_path, 'r').read()

class Auth(object):
    '''
    The Auth class provides the sequence for setting up communication with
    the master server from a minion.
    '''
    def __init__(self, opts):
        self.opts = opts
        self.token = Crypticle.generate_key_string()
        self.serial = salt.payload.Serial(self.opts)
        self.pub_path = os.path.join(self.opts['pki_dir'], 'minion.pub')
        self.rsa_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
        if 'syndic_master' in self.opts:
            self.mpub = 'syndic_master.pub'
        elif 'alert_master' in self.opts:
            self.mpub = 'monitor_master.pub'
        else:
            self.mpub = 'minion_master.pub'

    def get_keys(self):
        '''
        Returns a key objects for the minion
        '''
        # Make sure all key parent directories are accessible
        user = self.opts.get('user', 'root')
        salt.utils.verify.check_path_traversal(self.opts['pki_dir'], user)

        if os.path.exists(self.rsa_path):
            key = RSA.load_key(self.rsa_path)
            log.debug('Loaded minion key: {0}'.format(self.rsa_path))
        else:
            log.info('Generating keys: {0}'.format(self.opts['pki_dir']))
            gen_keys(
                    self.opts['pki_dir'],
                    'minion',
                    4096,
                    self.opts.get('user'))
            key = RSA.load_key(self.rsa_path)
        return key

    def minion_sign_in_payload(self):
        '''
        Generates the payload used to authenticate with the master
        server. This payload consists of the passed in id_ and the ssh
        public key to encrypt the AES key sent back form the master.
        '''
        payload = {}
        key = self.get_keys()
        tmp_pub = salt.utils.mkstemp()
        key.save_pub_key(tmp_pub)
        payload['enc'] = 'clear'
        payload['load'] = {}
        payload['load']['cmd'] = '_auth'
        payload['load']['id'] = self.opts['id']
        try:
            pub = RSA.load_pub_key(os.path.join(self.opts['pki_dir'], self.mpub))
            payload['load']['token'] = pub.public_encrypt(self.token, 4)
        except Exception:
            pass
        with salt.utils.fopen(tmp_pub, 'r') as fp_:
            payload['load']['pub'] = fp_.read()
        os.remove(tmp_pub)
        return payload

    def decrypt_aes(self, payload, master_pub=True):
        '''
        This function is used to decrypt the aes seed phrase returned from
        the master server, the seed phrase is decrypted with the ssh rsa
        host key.

        Pass in the encrypted aes key.
        Returns the decrypted aes seed key, a string
        '''
        log.debug('Decrypting the current master AES key')
        key = self.get_keys()
        key_str = key.private_decrypt(payload['aes'], 4)
        if 'sig' in payload:
            m_path = os.path.join(self.opts['pki_dir'], self.mpub)
            if os.path.exists(m_path):
                try:
                    mkey = RSA.load_pub_key(m_path)
                except Exception:
                    return '', ''
                digest = hashlib.sha256(key_str).hexdigest()
                m_digest = mkey.public_decrypt(payload['sig'], 5)
                if m_digest != digest:
                    return '', ''
        else:
            return '', ''
        if '_|-' in key_str:
            return key_str.split('_|-')
        else:
            if 'token' in payload:
                token = key.private_decrypt(payload['token'], 4)
                return key_str, token
            elif not master_pub:
                return key_str, ''
        return '', ''

    def verify_master(self, payload):
        '''
        '''
        m_pub_fn = os.path.join(self.opts['pki_dir'], self.mpub)
        if os.path.isfile(m_pub_fn) and not self.opts['open_mode']:
            local_master_pub = salt.utils.fopen(m_pub_fn).read()
            if payload['pub_key'] != local_master_pub:
                # This is not the last master we connected to
                log.error('The master key has changed, the salt master could '
                          'have been subverted, verify salt master\'s public '
                          'key')
                return ''
            try:
                aes, token = self.decrypt_aes(payload)
                if token != self.token:
                    log.error('The master failed to decrypt the random minion token')
                    return ''
            except Exception:
                log.error('The master failed to decrypt the random minion token')
                return ''
            return aes
        else:
            salt.utils.fopen(m_pub_fn, 'w+').write(payload['pub_key'])
            aes, token = self.decrypt_aes(payload, False)
            return aes

    def sign_in(self, timeout=60, safe=True):
        '''
        Send a sign in request to the master, sets the key information and
        returns a dict containing the master publish interface to bind to
        and the decrypted aes key for transport decryption.
        '''
        auth = {}
        m_pub_fn = os.path.join(self.opts['pki_dir'], self.mpub)
        try:
            self.opts['master_ip'] = salt.utils.dns_check(
                    self.opts['master'],
                    True,
                    self.opts['ipv6']
                    )
        except SaltClientError:
            if safe:
                return 'retry'
            else:
                raise SaltClientError
        sreq = salt.payload.SREQ(
                self.opts['master_uri'],
                self.opts.get('id', '')
                )
        try:
            payload = sreq.send_auto(
                    self.minion_sign_in_payload(),
                    timeout=timeout)
        except SaltReqTimeoutError:
            if safe:
                return 'retry'
            else:
                raise SaltClientError
        if 'load' in payload:
            if 'ret' in payload['load']:
                if not payload['load']['ret']:
                    log.critical(
                        'The Salt Master has rejected this minion\'s public '
                        'key!\nTo repair this issue, delete the public key '
                        'for this minion on the Salt Master and restart this '
                        'minion.\nOr restart the Salt Master in open mode to '
                        'clean out the keys. The Salt Minion will now exit.'
                    )
                    sys.exit(0)
                else:
                    log.error(
                        'The Salt Master has cached the public key for this '
                        'node, this salt minion will wait for {0} seconds '
                        'before attempting to re-authenticate'.format(
                            self.opts['acceptance_wait_time']
                        )
                    )
                    return 'retry'
        auth['aes'] = self.verify_master(payload)
        if not auth['aes']:
            log.critical(
                'The Salt Master server\'s public key did not authenticate!\n'
                'The master may need to be updated if it is a version of Salt '
                'lower than {0}, or\n'
                'If you are confident that you are connecting to a valid Salt '
                'Master, then remove the master public key and restart the '
                'Salt Minion.\nThe master public key can be found '
                'at:\n{1}'.format(salt.version.__version__, m_pub_fn)
            )
            sys.exit(42)
        if self.opts.get('master_finger', False):
            if salt.utils.pem_finger(m_pub_fn) != self.opts['master_finger']:
                log.critical((
                    'The specified fingerprint in the master configuration '
                    'file:\n{0}\nDoes not match the authenticating master\'s '
                    'key:\n{1}\nVerify that the configured fingerprint '
                    'matches the fingerprint of the correct master and that '
                    'this minion is not subject to a man in the middle attack'
                    ).format(
                        self.opts['master_finger'],
                        salt.utils.pem_finger(m_pub_fn)
                        )
                    )
                sys.exit(42)
        auth['publish_port'] = payload['publish_port']
        return auth

class Crypticle(object):
    '''
    Authenticated encryption class

    Encryption algorithm: AES-CBC
    Signing algorithm: HMAC-SHA256
    '''

    PICKLE_PAD = 'pickle::'
    AES_BLOCK_SIZE = 16
    SIG_SIZE = hashlib.sha256().digest_size

    def __init__(self, opts, key_string, key_size=192):
        self.keys = self.extract_keys(key_string, key_size)
        self.key_size = key_size
        self.serial = salt.payload.Serial(opts)

    @classmethod
    def generate_key_string(cls, key_size=192):
        key = os.urandom(key_size // 8 + cls.SIG_SIZE)
        return key.encode('base64').replace('\n', '')

    @classmethod
    def extract_keys(cls, key_string, key_size):
        key = key_string.decode('base64')
        assert len(key) == key_size / 8 + cls.SIG_SIZE, 'invalid key'
        return key[:-cls.SIG_SIZE], key[-cls.SIG_SIZE:]

    def encrypt(self, data):
        '''
        encrypt data with AES-CBC and sign it with HMAC-SHA256
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        data = data + pad * chr(pad)
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = iv_bytes + cypher.encrypt(data)
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig

    def decrypt(self, data):
        '''
        verify HMAC-SHA256 signature and decrypt data with AES-CBC
        '''
        aes_key, hmac_key = self.keys
        sig = data[-self.SIG_SIZE:]
        data = data[:-self.SIG_SIZE]
        mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest()
        if len(mac_bytes) != len(sig):
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        result = 0
        for zipped_x, zipped_y in zip(mac_bytes, sig):
            result |= ord(zipped_x) ^ ord(zipped_y)
        if result != 0:
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        iv_bytes = data[:self.AES_BLOCK_SIZE]
        data = data[self.AES_BLOCK_SIZE:]
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = cypher.decrypt(data)
        return data[:-ord(data[-1])]

    def dumps(self, obj):
        '''
        Serialize and encrypt a python object
        '''
        return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj))

    def loads(self, data):
        '''
        Decrypt and un-serialize a python object
        '''
        data = self.decrypt(data)
        # simple integrity check to verify that we got meaningful data
        if not data.startswith(self.PICKLE_PAD):
            return {}
        return self.serial.loads(data[len(self.PICKLE_PAD):])

class SAuth(Auth):
    '''
    Set up an object to maintain the standalone authentication session
    with the salt master
    '''
    def __init__(self, opts):
        super(SAuth, self).__init__(opts)
        self.crypticle = self.__authenticate()

    def __authenticate(self):
        '''
        Authenticate with the master, this method breaks the functional
        paradigm, it will update the master information from a fresh sign
        in, signing in can occur as often as needed to keep up with the
        revolving master aes key.
        '''
        while True:
            creds = self.sign_in()
            if creds == 'retry':
                if self.opts.get('caller'):
                    msg = ('Minion failed to authenticate with the master, '
                           'has the minion key been accepted?')
                    print(msg)
                    sys.exit(2)
                continue
            break
        return Crypticle(self.opts, creds['aes'])

    def gen_token(self, clear_tok):
        '''
        Encrypt a string with the minion private key to verify identity
        with the master.
        '''
        return self.get_keys().private_encrypt(clear_tok, 5)
<commit_msg>Allow SAuth to pass timeout and safe into sign_in<commit_after>'''
The crypt module manages all of the cryptography functions for minions and
masters, encrypting and decrypting payloads, preparing messages, and
authenticating peers
'''

# Import python libs
import os
import sys
import hmac
import hashlib
import logging

# Import third party libs
from M2Crypto import RSA
from Crypto.Cipher import AES

# Import salt libs
import salt.utils
import salt.payload
import salt.utils.verify
import salt.version
from salt.exceptions import (
    AuthenticationError, SaltClientError, SaltReqTimeoutError
)

log = logging.getLogger(__name__)

def dropfile(cachedir):
    '''
    Set an aes dropfile to update the publish session key
    '''
    dfn = os.path.join(cachedir, '.dfn')
    aes = Crypticle.generate_key_string()
    mask = os.umask(191)
    with open(dfn, 'w+') as fp_:
        fp_.write(aes)
    os.umask(mask)

def gen_keys(keydir, keyname, keysize, user=None):
    '''
    Generate a keypair for use with salt
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)

    gen = RSA.gen_key(keysize, 65537, callback=lambda x, y, z: None)
    cumask = os.umask(191)
    gen.save_key(priv, None)
    os.umask(cumask)
    gen.save_pub_key(pub)
    os.chmod(priv, 256)
    if user:
        try:
            import pwd
            uid = pwd.getpwnam(user).pw_uid
            os.chown(priv, uid, -1)
            os.chown(pub, uid, -1)
        except (KeyError, ImportError, OSError):
            # The specified user was not found, allow the backup systems to
            # report the error
            pass
    return priv

class MasterKeys(dict):
    '''
    The Master Keys class is used to manage the public key pair used for
    authentication by the master.
    '''
    def __init__(self, opts):
        super(MasterKeys, self).__init__()
        self.opts = opts
        self.pub_path = os.path.join(self.opts['pki_dir'], 'master.pub')
        self.rsa_path = os.path.join(self.opts['pki_dir'], 'master.pem')
        self.key = self.__get_keys()
        self.token = self.__gen_token()

    def __get_keys(self):
        '''
        Returns a key objects for the master
        '''
        if os.path.exists(self.rsa_path):
            key = RSA.load_key(self.rsa_path)
            log.debug('Loaded master key: {0}'.format(self.rsa_path))
        else:
            log.info('Generating keys: {0}'.format(self.opts['pki_dir']))
            gen_keys(
                    self.opts['pki_dir'],
                    'master',
                    4096,
                    self.opts.get('user'))
            key = RSA.load_key(self.rsa_path)
        return key

    def __gen_token(self):
        '''
        Generate the authentication token
        '''
        return self.key.private_encrypt('salty bacon', 5)

    def get_pub_str(self):
        '''
        Return the string representation of the public key
        '''
        if not os.path.isfile(self.pub_path):
            key = self.__get_keys()
            key.save_pub_key(self.pub_path)
        return salt.utils.fopen(self.pub_path, 'r').read()

class Auth(object):
    '''
    The Auth class provides the sequence for setting up communication with
    the master server from a minion.
    '''
    def __init__(self, opts):
        self.opts = opts
        self.token = Crypticle.generate_key_string()
        self.serial = salt.payload.Serial(self.opts)
        self.pub_path = os.path.join(self.opts['pki_dir'], 'minion.pub')
        self.rsa_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
        if 'syndic_master' in self.opts:
            self.mpub = 'syndic_master.pub'
        elif 'alert_master' in self.opts:
            self.mpub = 'monitor_master.pub'
        else:
            self.mpub = 'minion_master.pub'

    def get_keys(self):
        '''
        Returns a key objects for the minion
        '''
        # Make sure all key parent directories are accessible
        user = self.opts.get('user', 'root')
        salt.utils.verify.check_path_traversal(self.opts['pki_dir'], user)

        if os.path.exists(self.rsa_path):
            key = RSA.load_key(self.rsa_path)
            log.debug('Loaded minion key: {0}'.format(self.rsa_path))
        else:
            log.info('Generating keys: {0}'.format(self.opts['pki_dir']))
            gen_keys(
                    self.opts['pki_dir'],
                    'minion',
                    4096,
                    self.opts.get('user'))
            key = RSA.load_key(self.rsa_path)
        return key

    def minion_sign_in_payload(self):
        '''
        Generates the payload used to authenticate with the master
        server. This payload consists of the passed in id_ and the ssh
        public key to encrypt the AES key sent back form the master.
        '''
        payload = {}
        key = self.get_keys()
        tmp_pub = salt.utils.mkstemp()
        key.save_pub_key(tmp_pub)
        payload['enc'] = 'clear'
        payload['load'] = {}
        payload['load']['cmd'] = '_auth'
        payload['load']['id'] = self.opts['id']
        try:
            pub = RSA.load_pub_key(os.path.join(self.opts['pki_dir'], self.mpub))
            payload['load']['token'] = pub.public_encrypt(self.token, 4)
        except Exception:
            pass
        with salt.utils.fopen(tmp_pub, 'r') as fp_:
            payload['load']['pub'] = fp_.read()
        os.remove(tmp_pub)
        return payload

    def decrypt_aes(self, payload, master_pub=True):
        '''
        This function is used to decrypt the aes seed phrase returned from
        the master server, the seed phrase is decrypted with the ssh rsa
        host key.

        Pass in the encrypted aes key.
        Returns the decrypted aes seed key, a string
        '''
        log.debug('Decrypting the current master AES key')
        key = self.get_keys()
        key_str = key.private_decrypt(payload['aes'], 4)
        if 'sig' in payload:
            m_path = os.path.join(self.opts['pki_dir'], self.mpub)
            if os.path.exists(m_path):
                try:
                    mkey = RSA.load_pub_key(m_path)
                except Exception:
                    return '', ''
                digest = hashlib.sha256(key_str).hexdigest()
                m_digest = mkey.public_decrypt(payload['sig'], 5)
                if m_digest != digest:
                    return '', ''
        else:
            return '', ''
        if '_|-' in key_str:
            return key_str.split('_|-')
        else:
            if 'token' in payload:
                token = key.private_decrypt(payload['token'], 4)
                return key_str, token
            elif not master_pub:
                return key_str, ''
        return '', ''

    def verify_master(self, payload):
        '''
        '''
        m_pub_fn = os.path.join(self.opts['pki_dir'], self.mpub)
        if os.path.isfile(m_pub_fn) and not self.opts['open_mode']:
            local_master_pub = salt.utils.fopen(m_pub_fn).read()
            if payload['pub_key'] != local_master_pub:
                # This is not the last master we connected to
                log.error('The master key has changed, the salt master could '
                          'have been subverted, verify salt master\'s public '
                          'key')
                return ''
            try:
                aes, token = self.decrypt_aes(payload)
                if token != self.token:
                    log.error('The master failed to decrypt the random minion token')
                    return ''
            except Exception:
                log.error('The master failed to decrypt the random minion token')
                return ''
            return aes
        else:
            salt.utils.fopen(m_pub_fn, 'w+').write(payload['pub_key'])
            aes, token = self.decrypt_aes(payload, False)
            return aes

    def sign_in(self, timeout=60, safe=True):
        '''
        Send a sign in request to the master, sets the key information and
        returns a dict containing the master publish interface to bind to
        and the decrypted aes key for transport decryption.
        '''
        auth = {}
        m_pub_fn = os.path.join(self.opts['pki_dir'], self.mpub)
        try:
            self.opts['master_ip'] = salt.utils.dns_check(
                    self.opts['master'],
                    True,
                    self.opts['ipv6']
                    )
        except SaltClientError:
            if safe:
                return 'retry'
            else:
                raise SaltClientError
        sreq = salt.payload.SREQ(
                self.opts['master_uri'],
                self.opts.get('id', '')
                )
        try:
            payload = sreq.send_auto(
                    self.minion_sign_in_payload(),
                    timeout=timeout)
        except SaltReqTimeoutError:
            if safe:
                return 'retry'
            else:
                raise SaltClientError
        if 'load' in payload:
            if 'ret' in payload['load']:
                if not payload['load']['ret']:
                    log.critical(
                        'The Salt Master has rejected this minion\'s public '
                        'key!\nTo repair this issue, delete the public key '
                        'for this minion on the Salt Master and restart this '
                        'minion.\nOr restart the Salt Master in open mode to '
                        'clean out the keys. The Salt Minion will now exit.'
                    )
                    sys.exit(0)
                else:
                    log.error(
                        'The Salt Master has cached the public key for this '
                        'node, this salt minion will wait for {0} seconds '
                        'before attempting to re-authenticate'.format(
                            self.opts['acceptance_wait_time']
                        )
                    )
                    return 'retry'
        auth['aes'] = self.verify_master(payload)
        if not auth['aes']:
            log.critical(
                'The Salt Master server\'s public key did not authenticate!\n'
                'The master may need to be updated if it is a version of Salt '
                'lower than {0}, or\n'
                'If you are confident that you are connecting to a valid Salt '
                'Master, then remove the master public key and restart the '
                'Salt Minion.\nThe master public key can be found '
                'at:\n{1}'.format(salt.version.__version__, m_pub_fn)
            )
            sys.exit(42)
        if self.opts.get('master_finger', False):
            if salt.utils.pem_finger(m_pub_fn) != self.opts['master_finger']:
                log.critical((
                    'The specified fingerprint in the master configuration '
                    'file:\n{0}\nDoes not match the authenticating master\'s '
                    'key:\n{1}\nVerify that the configured fingerprint '
                    'matches the fingerprint of the correct master and that '
                    'this minion is not subject to a man in the middle attack'
                    ).format(
                        self.opts['master_finger'],
                        salt.utils.pem_finger(m_pub_fn)
                        )
                    )
                sys.exit(42)
        auth['publish_port'] = payload['publish_port']
        return auth

class Crypticle(object):
    '''
    Authenticated encryption class

    Encryption algorithm: AES-CBC
    Signing algorithm: HMAC-SHA256
    '''

    PICKLE_PAD = 'pickle::'
    AES_BLOCK_SIZE = 16
    SIG_SIZE = hashlib.sha256().digest_size

    def __init__(self, opts, key_string, key_size=192):
        self.keys = self.extract_keys(key_string, key_size)
        self.key_size = key_size
        self.serial = salt.payload.Serial(opts)

    @classmethod
    def generate_key_string(cls, key_size=192):
        key = os.urandom(key_size // 8 + cls.SIG_SIZE)
        return key.encode('base64').replace('\n', '')

    @classmethod
    def extract_keys(cls, key_string, key_size):
        key = key_string.decode('base64')
        assert len(key) == key_size / 8 + cls.SIG_SIZE, 'invalid key'
        return key[:-cls.SIG_SIZE], key[-cls.SIG_SIZE:]

    def encrypt(self, data):
        '''
        encrypt data with AES-CBC and sign it with HMAC-SHA256
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        data = data + pad * chr(pad)
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = iv_bytes + cypher.encrypt(data)
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig

    def decrypt(self, data):
        '''
        verify HMAC-SHA256 signature and decrypt data with AES-CBC
        '''
        aes_key, hmac_key = self.keys
        sig = data[-self.SIG_SIZE:]
        data = data[:-self.SIG_SIZE]
        mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest()
        if len(mac_bytes) != len(sig):
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        result = 0
        for zipped_x, zipped_y in zip(mac_bytes, sig):
            result |= ord(zipped_x) ^ ord(zipped_y)
        if result != 0:
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        iv_bytes = data[:self.AES_BLOCK_SIZE]
        data = data[self.AES_BLOCK_SIZE:]
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = cypher.decrypt(data)
        return data[:-ord(data[-1])]

    def dumps(self, obj):
        '''
        Serialize and encrypt a python object
        '''
        return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj))

    def loads(self, data):
        '''
        Decrypt and un-serialize a python object
        '''
        data = self.decrypt(data)
        # simple integrity check to verify that we got meaningful data
        if not data.startswith(self.PICKLE_PAD):
            return {}
        return self.serial.loads(data[len(self.PICKLE_PAD):])

class SAuth(Auth):
    '''
    Set up an object to maintain the standalone authentication session
    with the salt master
    '''
    def __init__(self, opts):
        super(SAuth, self).__init__(opts)
        self.crypticle = self.__authenticate()

    def __authenticate(self):
        '''
        Authenticate with the master, this method breaks the functional
        paradigm, it will update the master information from a fresh sign
        in, signing in can occur as often as needed to keep up with the
        revolving master aes key.
        '''
        while True:
            creds = self.sign_in(
                    self.opts.get('_auth_timeout', 60),
                    self.opts.get('_safe_auth', True)
                    )
            if creds == 'retry':
                if self.opts.get('caller'):
                    msg = ('Minion failed to authenticate with the master, '
                           'has the minion key been accepted?')
                    print(msg)
                    sys.exit(2)
                continue
            break
        return Crypticle(self.opts, creds['aes'])

    def gen_token(self, clear_tok):
        '''
        Encrypt a string with the minion private key to verify identity
        with the master.
        '''
        return self.get_keys().private_encrypt(clear_tok, 5)
<|endoftext|>


<commit_before>#!/bin/evn python
import discord
import json
import requests
import requests_cache
from discord.ext import commands

with open("data/apikeys.json") as f:
    news_api_key = json.load(f)["news"]

uri = "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey={}"

class News():
    def __init__(self, bot):
        self.bot = bot

    @commands.bot.command(name="news")
    async def get_news(self, num_results=3):
        """ Get the top x articles from Google News (powered by https://newsapi.org/) """

        if num_results > 5:
            return await self.bot.say("Sorry, please choose a number of results between 0 and 5 inclusive.")

        # Call to API
        raw_result = requests.get(uri.format(news_api_key)).json()

        article_list = []

        for x in range(num_results):
            article_list.append(
                "".join(["`", raw_result["articles"][x]["title"], "`"]))
            article_list.append(
                "".join(["<", raw_result["articles"][x]["url"], ">"]))

        # Found a better way
        return await self.bot.say("\n".join(article_list))

def setup(bot):
    bot.add_cog(News(bot))
<commit_msg>remove empty message exception in news<commit_after>#!/bin/evn python
import discord
import json
import requests
import requests_cache
from discord.ext import commands

with open("data/apikeys.json") as f:
    news_api_key = json.load(f)["news"]

uri = "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey={}"

class News():
    def __init__(self, bot):
        self.bot = bot

    @commands.bot.command(name="news")
    async def get_news(self, num_results=3):
        """ Get the top x articles from Google News (powered by https://newsapi.org/) """

        if num_results < 1 or num_results > 5:
            return await self.bot.say("Sorry, please choose a number of results between 1 and 5 inclusive.")

        # Call to API
        raw_result = requests.get(uri.format(news_api_key)).json()

        article_list = []

        for x in range(num_results):
            article_list.append(
                "".join(["`", raw_result["articles"][x]["title"], "`"]))
            article_list.append(
                "".join(["<", raw_result["articles"][x]["url"], ">"]))

        # Found a better way
        return await self.bot.say("\n".join(article_list))

def setup(bot):
    bot.add_cog(News(bot))
<|endoftext|>


<commit_before>"""This module/cog is taken from Rapptz/Danny's RoboDanny bot. Don't sue me."""

from discord.ext import commands
from .utils import checks
import asyncio
import traceback
import discord
import inspect
from contextlib import redirect_stdout
import io

class REPL:
    def __init__(self, bot):
        self.bot = bot
        self.sessions = set()

    def cleanup_code(self, content):
        """Automatically removes code blocks from the code."""
        # remove ```py\n```
        if content.startswith('```') and content.endswith('```'):
            return '\n'.join(content.split('\n')[1:-1])

        # remove `foo`
        return content.strip('` \n')

    def get_syntax_error(self, e):
        return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)

    @commands.command(pass_context=True, hidden=True)
    @checks.is_owner()
    async def repl(self, ctx):
        msg = ctx.message

        variables = {
            'ctx': ctx,
            'bot': self.bot,
            'message': msg,
            'server': msg.server,
            'channel': msg.channel,
            'author': msg.author,
            'last': None,
        }

        if msg.channel.id in self.sessions:
            await self.bot.say('Already running a REPL session in this channel. Exit it with `quit`.')
            return

        self.sessions.add(msg.channel.id)
        await self.bot.say('Enter code to execute or evaluate. `exit()` or `quit` to exit.')
        while True:
            response = await self.bot.wait_for_message(author=msg.author, channel=msg.channel,
                                                       check=lambda m: m.content.startswith('`'))

            cleaned = self.cleanup_code(response.content)

            if cleaned in ('quit', 'exit', 'exit()'):
                await self.bot.say('Exiting.')
                self.sessions.remove(msg.channel.id)
                return

            executor = exec
            if cleaned.count('\n') == 0:
                # single statement, potentially 'eval'
                try:
                    code = compile(cleaned, '<repl session>', 'eval')
                except SyntaxError:
                    pass
                else:
                    executor = eval

            if executor is exec:
                try:
                    code = compile(cleaned, '<repl session>', 'exec')
                except SyntaxError as e:
                    await self.bot.say(self.get_syntax_error(e))
                    continue

            variables['message'] = response

            fmt = None
            stdout = io.StringIO()

            try:
                with redirect_stdout(stdout):
                    result = executor(code, variables)
                    if inspect.isawaitable(result):
                        result = await result
            except Exception as e:
                value = stdout.getvalue()
                fmt = '```py\n{}{}\n```'.format(value, traceback.format_exc())
            else:
                value = stdout.getvalue()
                if result is not None:
                    fmt = '```py\n{}{}\n```'.format(value, result)
                    variables['last'] = result
                elif value:
                    fmt = '```py\n{}\n```'.format(value)

            try:
                if fmt is not None:
                    if len(fmt) > 2000:
                        await self.bot.send_message(msg.channel, 'Content too big to be printed.')
                    else:
                        await self.bot.send_message(msg.channel, fmt)
            except discord.Forbidden:
                pass
            except discord.HTTPException as e:
                await self.bot.send_message(msg.channel, 'Unexpected error: `{}`'.format(e))

def setup(bot):
    bot.add_cog(REPL(bot))
<commit_msg>add Danny's debug/eval command to repl cog<commit_after>"""This module/cog is taken from Rapptz/Danny's RoboDanny bot. Don't sue me."""

from discord.ext import commands
from .utils import checks
import asyncio
import traceback
import discord
import inspect
from contextlib import redirect_stdout
import io

class REPL:
    def __init__(self, bot):
        self.bot = bot
        self.sessions = set()

    def cleanup_code(self, content):
        """Automatically removes code blocks from the code."""
        # remove ```py\n```
        if content.startswith('```') and content.endswith('```'):
            return '\n'.join(content.split('\n')[1:-1])

        # remove `foo`
        return content.strip('` \n')

    def get_syntax_error(self, e):
        return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)

    @commands.command(pass_context=True, hidden=True)
    @checks.is_owner()
    async def repl(self, ctx):
        msg = ctx.message

        variables = {
            'ctx': ctx,
            'bot': self.bot,
            'message': msg,
            'server': msg.server,
            'channel': msg.channel,
            'author': msg.author,
            'last': None,
        }

        if msg.channel.id in self.sessions:
            await self.bot.say('Already running a REPL session in this channel. Exit it with `quit`.')
            return

        self.sessions.add(msg.channel.id)
        await self.bot.say('Enter code to execute or evaluate. `exit()` or `quit` to exit.')
        while True:
            response = await self.bot.wait_for_message(author=msg.author, channel=msg.channel,
                                                       check=lambda m: m.content.startswith('`'))

            cleaned = self.cleanup_code(response.content)

            if cleaned in ('quit', 'exit', 'exit()'):
                await self.bot.say('Exiting.')
                self.sessions.remove(msg.channel.id)
                return

            executor = exec
            if cleaned.count('\n') == 0:
                # single statement, potentially 'eval'
                try:
                    code = compile(cleaned, '<repl session>', 'eval')
                except SyntaxError:
                    pass
                else:
                    executor = eval

            if executor is exec:
                try:
                    code = compile(cleaned, '<repl session>', 'exec')
                except SyntaxError as e:
                    await self.bot.say(self.get_syntax_error(e))
                    continue

            variables['message'] = response

            fmt = None
            stdout = io.StringIO()

            try:
                with redirect_stdout(stdout):
                    result = executor(code, variables)
                    if inspect.isawaitable(result):
                        result = await result
            except Exception as e:
                value = stdout.getvalue()
                fmt = '```py\n{}{}\n```'.format(value, traceback.format_exc())
            else:
                value = stdout.getvalue()
                if result is not None:
                    fmt = '```py\n{}{}\n```'.format(value, result)
                    variables['last'] = result
                elif value:
                    fmt = '```py\n{}\n```'.format(value)

            try:
                if fmt is not None:
                    if len(fmt) > 2000:
                        await self.bot.send_message(msg.channel, 'Content too big to be printed.')
                    else:
                        await self.bot.send_message(msg.channel, fmt)
            except discord.Forbidden:
                pass
            except discord.HTTPException as e:
                await self.bot.send_message(msg.channel, 'Unexpected error: `{}`'.format(e))

    @commands.command(pass_context=True, hidden=True, name='eval')
    @checks.is_owner()
    async def debug(self, ctx, *, code : str):
        """Evaluates code."""
        code = code.strip('` ')
        python = '```py\n{}\n```'
        result = None

        env = {
            'bot': self.bot,
            'ctx': ctx,
            'message': ctx.message,
            'server': ctx.message.server,
            'channel': ctx.message.channel,
            'author': ctx.message.author
        }

        env.update(globals())

        try:
            result = eval(code, env)
            if inspect.isawaitable(result):
                result = await result
        except Exception as e:
            await self.bot.say(python.format(type(e).__name__ + ': ' + str(e)))
            return

        await self.bot.say(python.format(result))

def setup(bot):
    bot.add_cog(REPL(bot))
<|endoftext|>


<commit_before># coding: utf-8

import tempfile
import os
import shutil
import time
from nose.tools import assert_equals, assert_not_equals, with_setup
import common
from waiting import wait
from swagger_client.rest import ApiException

from swagger_client.models.tx import Tx
from swagger_client.models.spend_tx import SpendTx
from swagger_client.models.contract_create_data import ContractCreateData
from swagger_client.models.contract_call_data import ContractCallData
from swagger_client.models.contract_call_input import ContractCallInput

settings = common.test_settings(__name__.split(".")[-1])

def test_contract_create():
    test_settings = settings["test_contract_create"]
    (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node")
    internal_api = common.internal_api(node)

    send_tokens_to_user("alice", test_settings, internal_api, external_api)

    encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], test_settings["create_contract"], external_api)

    print("Unsigned encoded transaction: " + encoded_tx)
    unsigned_tx = common.base58_decode(encoded_tx)
    unpacked_tx = common.unpack_tx(unsigned_tx)
    tx = common.parse_tx(unpacked_tx)
    print("Unsigned decoded transaction: " + str(tx))

    # make sure same tx
    assert_equals(tx['type'], 'contract_create')
    assert_equals(tx['owner'], common.base58_decode(test_settings["alice"]["pubkey"]))
    assert_equals(tx['vm_version'], test_settings["create_contract"]["vm_version"])
    assert_equals(tx['deposit'], test_settings["create_contract"]["deposit"])
    assert_equals(tx['amount'], test_settings["create_contract"]["amount"])
    assert_equals(tx['gas'], test_settings["create_contract"]["gas"])
    assert_equals(tx['gas_price'], test_settings["create_contract"]["gas_price"])
    assert_equals(tx['fee'], test_settings["create_contract"]["fee"])

    code = bytearray.fromhex(test_settings["create_contract"]["code"][2:]) # without 0x
    assert_equals(tx['code'], code)

    call_data = bytearray.fromhex(test_settings["create_contract"]["call_data"][2:]) # without 0x
    assert_equals(tx['call_data'], call_data)

    signature = bytearray(list(map(int, test_settings["create_contract"]["signature"].split(","))))
    signed = common.encode_signed_tx(unpacked_tx, [signature])
    print("Signed transaction " + signed)

    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    assert_equals(alice_balance0, alice_balance + test_settings["create_contract"]["fee"])

    cleanup(node, root_dir)

def test_contract_call():
    test_settings = settings["test_contract_call"]
    create_settings = settings["test_contract_create"]
    (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node")
    internal_api = common.internal_api(node)

    send_tokens_to_user("alice", test_settings, internal_api, external_api)

    ## create contract
    encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], create_settings["create_contract"], external_api)
    unsigned_tx = common.base58_decode(encoded_tx)
    unpacked_tx = common.unpack_tx(unsigned_tx)
    signature = bytearray(list(map(int, create_settings["create_contract"]["signature"].split(","))))
    signed = common.encode_signed_tx(unpacked_tx,[signature])

    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    # assert contract created:
    call_contract = test_settings["contract_call"]
    assert_equals(alice_balance0, alice_balance + create_settings["create_contract"]["fee"])

    call_input = ContractCallInput("ring", create_settings["create_contract"]["code"],\
                                           call_contract["data"]["function"],\
                                           call_contract["data"]["argument"])
    result = external_api.call_contract(call_input)
    contract_call_obj = ContractCallData(
        caller=test_settings["alice"]["pubkey"],
        contract=call_contract["contract"],
        vm_version=call_contract["vm_version"],
        fee=call_contract["fee"],
        amount=call_contract["amount"],
        gas=call_contract["gas"],
        gas_price=call_contract["gas_price"],
        call_data=result.out)

    call_tx_obj = external_api.post_contract_call(contract_call_obj)
    encoded_call_tx = call_tx_obj.tx

    print("Unsigned encoded transaction: " + encoded_call_tx)
    unsigned_call_tx = common.base58_decode(encoded_call_tx)
    unpacked_call_tx = common.unpack_tx(unsigned_call_tx)
    tx = common.parse_tx(unpacked_call_tx)
    print("Unsigned decoded transaction: " + str(tx))

    signature = bytearray(list(map(int, test_settings["contract_call"]["signature"].split(","))))

    signed = common.encode_signed_tx(unpacked_call_tx,[signature])

    print("Signed transaction: " + signed)
    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    print("BALANCE0 " + str(alice_balance0))
    print("BALANCE " + str(alice_balance))
    # assert contract created:
    assert_equals(alice_balance0, alice_balance + test_settings["contract_call"]["fee"])

    cleanup(node, root_dir)

def cleanup(node, root_dir):
    common.stop_node(node)
    shutil.rmtree(root_dir)

def make_mining_config(root_dir, file_name):
    sys_config = os.path.join(root_dir, file_name)
    f = open(sys_config, "w")
    # if autostart is not true - there will be no miner
    conf ='[{aecore, [{autostart, true},' + \
                    ' {expected_mine_rate, 100},' + \
                    ' {aec_pow_cuckoo, {"mean16s-generic", "-t 5", 16}}]}].'
    f.write(conf)
    f.close()
    return sys_config

def setup_node_with_tokens(test_settings, node_name):
    # prepare a dir to hold the configs and the keys
    root_dir = tempfile.mkdtemp()

    # setup the dir with Alice's node mining
    node = test_settings["nodes"][node_name]
    sys_config = make_mining_config(root_dir, "sys.config")
    common.start_node(node, sys_config)
    api = common.external_api(node)

    # populate the chain so Alice had mined some blocks and has tokens
    # to spend
    blocks_to_mine = test_settings["blocks_to_mine"]
    common.wait_until_height(api, blocks_to_mine)
    top = api.get_top()
    assert_equals(top.height >= blocks_to_mine, True)
    # Now the node has at least blocks_to_mine blocks mined by Alice

    return (root_dir, node, api, top)

def send_tokens_to_user(user, test_settings, internal_api, external_api):
    spend_tx_obj = SpendTx(
        recipient_pubkey=test_settings[user]["pubkey"],
        amount=test_settings[user]["amount"],
        fee=test_settings[user]["amount"])

    # populate Alice's account
    internal_api.post_spend_tx(spend_tx_obj)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)

    balance_obj = common.get_account_balance(internal_api, pub_key=test_settings[user]["pubkey"])
    print(user.capitalize() + "'s balance is now " + str(balance_obj.balance))

def get_unsigned_contract_create(owner, contract, external_api):
    contract_create_data_obj = ContractCreateData(
        owner=owner,
        code=contract["code"],
        vm_version=contract["vm_version"],
        deposit=contract["deposit"],
        amount=contract["amount"],
        gas=contract["gas"],
        gas_price=contract["gas_price"],
        fee=contract["fee"],
        call_data=contract["call_data"])

    tx_obj = external_api.post_contract_create(contract_create_data_obj)
    return tx_obj.tx
<commit_msg>Fix UAT test re contract create<commit_after># coding: utf-8

import tempfile
import os
import shutil
import time
from nose.tools import assert_equals, assert_not_equals, with_setup
import common
from waiting import wait
from swagger_client.rest import ApiException

from swagger_client.models.tx import Tx
from swagger_client.models.spend_tx import SpendTx
from swagger_client.models.contract_create_data import ContractCreateData
from swagger_client.models.contract_call_data import ContractCallData
from swagger_client.models.contract_call_input import ContractCallInput

settings = common.test_settings(__name__.split(".")[-1])

def test_contract_create():
    test_settings = settings["test_contract_create"]
    (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node")
    internal_api = common.internal_api(node)

    send_tokens_to_user("alice", test_settings, internal_api, external_api)

    encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], test_settings["create_contract"], external_api)

    print("Unsigned encoded transaction: " + encoded_tx)
    unsigned_tx = common.base58_decode(encoded_tx)
    unpacked_tx = common.unpack_tx(unsigned_tx)
    tx = common.parse_tx(unpacked_tx)
    print("Unsigned decoded transaction: " + str(tx))

    # make sure same tx
    assert_equals(tx['type'], 'aect_create_tx')
    assert_equals(tx['owner'], common.base58_decode(test_settings["alice"]["pubkey"]))
    assert_equals(tx['vm_version'], test_settings["create_contract"]["vm_version"])
    assert_equals(tx['deposit'], test_settings["create_contract"]["deposit"])
    assert_equals(tx['amount'], test_settings["create_contract"]["amount"])
    assert_equals(tx['gas'], test_settings["create_contract"]["gas"])
    assert_equals(tx['gas_price'], test_settings["create_contract"]["gas_price"])
    assert_equals(tx['fee'], test_settings["create_contract"]["fee"])

    code = bytearray.fromhex(test_settings["create_contract"]["code"][2:]) # without 0x
    assert_equals(tx['code'], code)

    call_data = bytearray.fromhex(test_settings["create_contract"]["call_data"][2:]) # without 0x
    assert_equals(tx['call_data'], call_data)

    signature = bytearray(list(map(int, test_settings["create_contract"]["signature"].split(","))))
    signed = common.encode_signed_tx(unpacked_tx, [signature])
    print("Signed transaction " + signed)

    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    assert_equals(alice_balance0, alice_balance + test_settings["create_contract"]["fee"])

    cleanup(node, root_dir)

def test_contract_call():
    test_settings = settings["test_contract_call"]
    create_settings = settings["test_contract_create"]
    (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node")
    internal_api = common.internal_api(node)

    send_tokens_to_user("alice", test_settings, internal_api, external_api)

    ## create contract
    encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], create_settings["create_contract"], external_api)
    unsigned_tx = common.base58_decode(encoded_tx)
    unpacked_tx = common.unpack_tx(unsigned_tx)
    signature = bytearray(list(map(int, create_settings["create_contract"]["signature"].split(","))))
    signed = common.encode_signed_tx(unpacked_tx,[signature])

    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    # assert contract created:
    call_contract = test_settings["contract_call"]
    assert_equals(alice_balance0, alice_balance + create_settings["create_contract"]["fee"])

    call_input = ContractCallInput("ring", create_settings["create_contract"]["code"],\
                                           call_contract["data"]["function"],\
                                           call_contract["data"]["argument"])
    result = external_api.call_contract(call_input)
    contract_call_obj = ContractCallData(
        caller=test_settings["alice"]["pubkey"],
        contract=call_contract["contract"],
        vm_version=call_contract["vm_version"],
        fee=call_contract["fee"],
        amount=call_contract["amount"],
        gas=call_contract["gas"],
        gas_price=call_contract["gas_price"],
        call_data=result.out)

    call_tx_obj = external_api.post_contract_call(contract_call_obj)
    encoded_call_tx = call_tx_obj.tx

    print("Unsigned encoded transaction: " + encoded_call_tx)
    unsigned_call_tx = common.base58_decode(encoded_call_tx)
    unpacked_call_tx = common.unpack_tx(unsigned_call_tx)
    tx = common.parse_tx(unpacked_call_tx)
    print("Unsigned decoded transaction: " + str(tx))

    signature = bytearray(list(map(int, test_settings["contract_call"]["signature"].split(","))))

    signed = common.encode_signed_tx(unpacked_call_tx,[signature])

    print("Signed transaction: " + signed)
    alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance
    tx_object = Tx(tx=signed)
    external_api.post_tx(tx_object)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)
    alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance

    print("BALANCE0 " + str(alice_balance0))
    print("BALANCE " + str(alice_balance))
    # assert contract created:
    assert_equals(alice_balance0, alice_balance + test_settings["contract_call"]["fee"])

    cleanup(node, root_dir)

def cleanup(node, root_dir):
    common.stop_node(node)
    shutil.rmtree(root_dir)

def make_mining_config(root_dir, file_name):
    sys_config = os.path.join(root_dir, file_name)
    f = open(sys_config, "w")
    # if autostart is not true - there will be no miner
    conf ='[{aecore, [{autostart, true},' + \
                    ' {expected_mine_rate, 100},' + \
                    ' {aec_pow_cuckoo, {"mean16s-generic", "-t 5", 16}}]}].'
    f.write(conf)
    f.close()
    return sys_config

def setup_node_with_tokens(test_settings, node_name):
    # prepare a dir to hold the configs and the keys
    root_dir = tempfile.mkdtemp()

    # setup the dir with Alice's node mining
    node = test_settings["nodes"][node_name]
    sys_config = make_mining_config(root_dir, "sys.config")
    common.start_node(node, sys_config)
    api = common.external_api(node)

    # populate the chain so Alice had mined some blocks and has tokens
    # to spend
    blocks_to_mine = test_settings["blocks_to_mine"]
    common.wait_until_height(api, blocks_to_mine)
    top = api.get_top()
    assert_equals(top.height >= blocks_to_mine, True)
    # Now the node has at least blocks_to_mine blocks mined by Alice

    return (root_dir, node, api, top)

def send_tokens_to_user(user, test_settings, internal_api, external_api):
    spend_tx_obj = SpendTx(
        recipient_pubkey=test_settings[user]["pubkey"],
        amount=test_settings[user]["amount"],
        fee=test_settings[user]["amount"])

    # populate Alice's account
    internal_api.post_spend_tx(spend_tx_obj)

    top = external_api.get_top()
    common.wait_until_height(external_api, top.height + 3)

    balance_obj = common.get_account_balance(internal_api, pub_key=test_settings[user]["pubkey"])
    print(user.capitalize() + "'s balance is now " + str(balance_obj.balance))

def get_unsigned_contract_create(owner, contract, external_api):
    contract_create_data_obj = ContractCreateData(
        owner=owner,
        code=contract["code"],
        vm_version=contract["vm_version"],
        deposit=contract["deposit"],
        amount=contract["amount"],
        gas=contract["gas"],
        gas_price=contract["gas_price"],
        fee=contract["fee"],
        call_data=contract["call_data"])

    tx_obj = external_api.post_contract_create(contract_create_data_obj)
    return tx_obj.tx
<|endoftext|>


<commit_before># Copyright 2015 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
:mod:`topology_test` --- SCION topology tests
=============================================
"""
# Stdlib
#from unittest.mock import patch
from ipaddress import IPv4Address, IPv6Address
from ipaddress import IPv4Address, IPv6Address

# External packages
import nose
import nose.tools as ntools
#import bitstring
#from bitstring import BitArray

# SCION
from lib.topology import (
    Element
)

class TestElementInit(object):
    """
    Unit tests for lib.topology.Element construction.
    """
    def test_basic(self):
        elem = Element()
        ntools.assert_is_none(elem.addr)
        ntools.assert_is_none(elem.addr_type)
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

    def test_ipv4(self):
        elem = Element('192.168.0.1', 'ipv4')
        ntools.assert_is_none(elem.addr)
        ntools.assert_is_instance(elem.addr_type, IPv4Address)
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

    def test_ipv6(self):
        elem = Element('2001:db8::', 'ipv6')
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

if __name__ == "__main__":
    nose.run(defaultTest=__name__)
<commit_msg>Fixed minor bug in topology_test.py<commit_after># Copyright 2015 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
:mod:`topology_test` --- SCION topology tests
=============================================
"""
# Stdlib
#from unittest.mock import patch
from ipaddress import IPv4Address, IPv6Address
from ipaddress import IPv4Address, IPv6Address

# External packages
import nose
import nose.tools as ntools
#import bitstring
#from bitstring import BitArray

# SCION
from lib.topology import (
    Element
)

class TestElementInit(object):
    """
    Unit tests for lib.topology.Element construction.
    """
    def test_basic(self):
        elem = Element()
        ntools.assert_is_none(elem.addr)
        ntools.assert_is_none(elem.addr_type)
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

    def test_ipv4(self):
        elem = Element('192.168.0.1', 'ipv4')
        ntools.assert_is_not_none(elem.addr)
        ntools.assert_is_instance(elem.addr_type, IPv4Address)
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

    def test_ipv6(self):
        elem = Element('2001:db8::', 'ipv6')
        ntools.assert_is_none(elem.to_addr)
        ntools.assert_is_none(elem.name)

if __name__ == "__main__":
    nose.run(defaultTest=__name__)
<|endoftext|>